In this Article
- Creating a Function without Arguments
- Calling a Function from a Sub Procedure
- Creating Functions
- Single Argument
- Multiple Arguments
- Optional Arguments
- Default Argument Value
- ByVal and ByRef
- Exit Function
- Using a Function from within an Excel Sheet
This tutorial will teach you to create and use functions with and without parameters in VBA
VBA contains a large amount of built-in functions for you to use, but you are also able to write your own. When you write code in VBA, you can write it in a Sub Procedure, or a Function Procedure. A Function Procedure is able to return a value to your code. This is extremely useful if you want VBA to perform a task to return a result. VBA functions can also be called from inside Excel, just like Excel’s built-in Excel functions.
Creating a Function without Arguments
To create a function you need to define the function by giving the function a name. The function can then be defined as a data type indicating the type of data you want the function to return.
You may want to create a function that returns a static value each time it is called – a bit like a constant.
Function GetValue() As Integer
GetValue = 50
End Function
If you were to run the function, the function would always return the value of 50.
You can also create functions that refer to objects in VBA but you need to use the Set Keyword to return the value from the function.
Function GetRange() as Range
Set GetRange = Range("A1:G4")
End Function
If you were to use the above function in your VBA code, the function would always return the range of cells A1 to G4 in whichever sheet you are working in.
Calling a Function from a Sub Procedure
Once you create a function, you can call it from anywhere else in your code by using a Sub Procedure to call the function.
The value of 50 would always be returned.
You can also call the GetRange function from a Sub Procedure.
In the above example, the GetRange Function is called by the Sub Procedure to bold the cells in the range object.
Creating Functions
Single Argument
You can also assign a parameter or parameters to your function. These parameters can be referred to as Arguments.
Function ConvertKilosToPounds (dblKilo as Double) as Double
ConvertKiloToPounds = dblKilo*2.2
End Function
We can then call the above function from a Sub Procedure in order to work out how many pounds a specific amount of kilos are.
A function can be a called from multiple procedures within your VBA code if required. This is very useful in that it stops you from having to write the same code over and over again. It also enables you to divide long procedures into small manageable functions.
In the above example, we have 2 procedures – each of them are using the Function to calculate the pound value of the kilos passed to them in the dblKilo Argument of the function.
Multiple Arguments
You can create a Function with multiple arguments and pass the values to the Function by way of a Sub Procedure.
Function CalculateDayDiff(Date1 as Date, Date2 as Date) as Double
CalculateDayDiff = Date2-Date1
End Function
We can then call the function to calculate the amount of days between 2 dates.
Optional Arguments
You can also pass Optional arguments to a Function. In other words, sometimes you may need the argument, and sometimes you may not – depending on what code you are using the Function with .
Function CalculateDayDiff(Date1 as Date, Optional Date2 as Date) as Double
'check for second date and if not there, make Date2 equal to today's date.
If Date2=0 then Date2 = Date
'calculate difference
CalculateDayDiff = Date2-Date1
End Function
VBA Coding Made Easy
Stop searching for VBA code online. Learn more about AutoMacro — A VBA Code Builder that allows beginners to code procedures from scratch with minimal coding knowledge and with many time-saving features for all users!
Learn More
Default Argument Value
You can also set the default value of the Optional arguments when you are creating the function so that if the user omits the argument, the value that you have put as default will be used instead.
Function CalculateDayDiff(Date1 as Date, Optional Date2 as Date="06/02/2020") as Double
'calculate difference
CalculateDayDiff = Date2-Date1
End Function
ByVal and ByRef
When you pass values to a function, you can use the ByVal or ByRef keywords. If you omit either of these, the ByRef is used as the default.
ByVal means that you are passing a copy of the variable to the function, whereas ByRef means you are referring to the original value of the variable. When you pass a copy of the variable (ByVal), the original value of the variable is NOT changed, but when you reference the variable, the original value of the variable is changed by the function.
Function GetValue(ByRef intA As Integer) As Integer
intA = intA * 4
GetValue = intA
End Function
In the function above, the ByRef could be omitted and the function would work the same way.
Function GetValue(intA As Integer) As Integer
intA = intA * 4
GetValue = intA
End Function
To call this function, we can run a sub-procedure.
Sub TestValues()
Dim intVal As Integer
'populate the variable with the value 10
intVal = 10
'run the GetValue function, and show the value in the immediate window
Debug.Print GetValue(intVal)
'show the value of the intVal variable in the immediate window
Debug.Print intVal
End Sub
Note that the debug windows show the value 40 both times. When you pass the variable IntVal to the function – the value of 10 is passed to the function, and multiplied by 4. Using the ByRef keyword (or omitting it altogether), will AMEND the value of the IntVal variable. This is shown when you show first the result of the function in the immediate window (40), and then the value of the IntVal variable in the debug window (also 40).
If we do NOT want to change the value of the original variable, we have to use ByVal in the function.
Function GetValue(ByVal intA As Integer) As Integer
intA = intA * 4
GetValue = intA
End Function
Now if we call the function from a sub-procedure, the value of the variable IntVal will remain at 10.
Exit Function
If you create a function that tests for a certain condition, and once the condition is found to be true, you want return the value from the function, you may need to add an Exit Function statement in your Function in order to exit the function before you have run through all the code in that function.
Function FindNumber(strSearch As String) As Integer
Dim i As Integer
'loop through each letter in the string
For i = 1 To Len(strSearch)
'if the letter is numeric, return the value to the function
If IsNumeric(Mid(strSearch, i, 1)) Then
FindNumber= Mid(strSearch, i, 1)
'then exit the function
Exit Function
End If
Next
FindNumber= 0
End Function
The function above will loop through the string that is provided until it finds a number, and then return that number from the string. It will only find the first number in the string as it will then Exit the function.
The function above can be called by a Sub routine such as the one below.
Sub CheckForNumber()
Dim NumIs as Integer
'pass a text string to the find number function
NumIs = FindNumber("Upper Floor, 8 Oak Lane, Texas")
'show the result in the immediate window
Debug.Print NumIs
End Sub
VBA Programming | Code Generator does work for you!
Using a Function from within an Excel Sheet
In addition to calling a function from your VBA code using a sub procedure, you can also call the function from within your Excel sheet. The functions that you have created should by default appear in your function list in the User Defined section of the function list.
Click on the fx to show the Insert Function dialog box.
Select User Defined from the Category List
Select the function you require from the available User Defined Functions (UDF’s).
Alternatively, when you start writing your function in Excel, the function should appear in the drop down list of functions.
If you do not want the function to be available inside an Excel sheet, you need to put the Private word in front of the word Function when you create the function in your VBA code.
Private Function CalculateDayDiff(Date1 as Date, Date2 as Date) as Double
CalculateDayDiff = Date2-Date1
End Function
It will now not appear in the drop down list showing the Excel functions available.
Interestingly enough, however, you can still use the function – it just will not appear in the list when looking for it!
If you have declared the second argument as Optional, you can omit it within the Excel sheet as well as within the VBA code.
You can also use the a function that you have created without arguments in your Excel sheet.
VBA code to call a function
The below example will help you to know how to call a function in Excel VBA Macros (it can be Excel VBA function, or user defined function). We generally create lot of function and we use the functions whenever and any time we want. The below example will help you to understand calling a simple function with and without parameters.
Calling a function Excel VBA
Here is the simple example to call the Now function to display the time. We use the Now function to get the System Current Time and Date.
'vba code to call a function Sub vba_code_to_call_a_function() MsgBox Now() End Sub
Calling a function Excel VBA: Function with Parameters
Here is the another example to call the Left function to extract the left part of a string. We use the left function to extract the left part of any string.
'vba code to call a function Sub vba_code_to_call_a_function_a() MsgBox Left("123", 2) End Sub
Calling a user defined Function Excel VBA
It is same as above, but we have to make sure that the functions is written before calling the function. Other wise it will though the run time error.
'User Defined Function Function mySum(ByVal A As Integer, ByVal B As Integer) mySum = A + B End Function 'vba code to call a the user defined function Sub vba_code_to_call_a_function_b() 'Calling udf MsgBox mySum(1, 5) End Sub
VBA code to Convert and Save the Excel to CSV – Instructions
Please follow the below step by step instructions to test this Example VBA Macro codes:
- Step 1: Open a New Excel workbook
- Step 2: Press Alt+F11 – This will open the VBA Editor (alternatively, you can open it from Developer Tab in Excel Ribbon)
- Step 3: Insert a code module from then insert menu of the VBE
- Step 4: Copy the above code and paste in the code module which have inserted in the above step
- Step 5: Now press F8 to debug the Macro to check how the VBA is calling the function while execution
A Powerful & Multi-purpose Templates for project management. Now seamlessly manage your projects, tasks, meetings, presentations, teams, customers, stakeholders and time. This page describes all the amazing new features and options that come with our premium templates.
Save Up to 85% LIMITED TIME OFFER
All-in-One Pack
120+ Project Management Templates
Essential Pack
50+ Project Management Templates
Excel Pack
50+ Excel PM Templates
PowerPoint Pack
50+ Excel PM Templates
MS Word Pack
25+ Word PM Templates
Ultimate Project Management Template
Ultimate Resource Management Template
Project Portfolio Management Templates
Related Posts
- Calling a function Excel VBA
- Calling a function Excel VBA: Function with Parameters
- Calling a user defined Function Excel VBA
- VBA code to Convert and Save the Excel to CSV – Instructions
VBA Reference
Effortlessly
Manage Your Projects
120+ Project Management Templates
Seamlessly manage your projects with our powerful & multi-purpose templates for project management.
120+ PM Templates Includes:
One Comment
-
Rajadurai16
March 16, 2017 at 4:18 PM — ReplyTimer vba codes
Dim binNew As Boolean
Dim TRows, THows, i As LongPrivate Sub UserForm_Click()
End Sub
Private Sub CmdClose_Click()
If CmdClose.Caption = “Close” Then
Unload Me
Else
CmdClose.Caption = “Close”
CmdNew.Enabled = True
CmdDelete.Enabled = True
End If
End SubPrivate Sub CmdNew_Click()
binNew = True
txtEmpNo.Text = ”
txtEmpName.Text = ”
txtAddr1.Text = ”
txtAddr2.Text = ”
txtAddr3.Text = ”CmdClose.Caption = “Cancel”
CmdNew.Enabled = False
CmdSave.Enabled = True
CmdDelete.Enabled = False
End SubPrivate Sub cmdSave_Click()
If Trim(txtEmpNo.Text) = ” Then
MsgBox “Enter Emp. No. “, vbCritical, “Save”
Exit Sub
End If
Call prSave
End SubPrivate Sub prSave()
If binNew = True Then
THows = Worksheets(“Data”).Range(“A1”).CurrentRegion.Rows.Count
With Worksheets(“Data”).Range(“A1″)
.Offset(THows, 0).Value = txtEmpNo.Text
.Offset(THows, 1).Value = txtEmpName.Text
.Offset(THows, 2).Value = txtAddr1.Text
.Offset(THows, 3).Value = txtAddr2.Text
.Offset(THows, 4).Value = txtAddr3.TextEnd With
txtEmpNo.Text = ”
txtEmpName.Text = ”
txtAddr1.Text = ”
txtAddr2.Text = ”
txtAddr3.Text = ”Call PrComboBoxFill
Else
For i = 2 To TRows
If Trim(Worksheets(“Data”).Cells(i, 1).Value) = Trim(ComboBox1.Text) Then
Worksheets(“Data”).Cells(i, 1).Value = txtEmpNo.Text
Worksheets(“Data”).Cells(i, 2).Value = txtEmpName.Text
Worksheets(“Data”).Cells(i, 3).Value = txtAddr1.Text
Worksheets(“Data”).Cells(i, 4).Value = txtAddr2.Text
Worksheets(“Data”).Cells(i, 5).Value = txtAddr3.TexttxtEmpNo.Text = ”
txtEmpName.Text = ”
txtAddr1.Text = ”
txtAddr2.Text = ”
txtAddr3.Text = ”Exit For
End If
Next i
End If
binNew = FalseEnd Sub
————————————-
Private Sub cmdDelete_Click()
TRows = Worksheets(“Data”).Range(“A1”).CurrentRegion.Rows.Count
Dim strDel
strDel = MagBox(“Delete ?”, vbYesNo, “Delete”)
If strDel = vbYes Then
For i = 2 To TRows
If Trims(Worksheets(“Data”).Cells(i, 1).Value) = Trim(ComboBox1.Text) Then‘ sheet1.range(i & “:” & i).Delete
Worksheets(“Data”).Range(i & “:” & i).DeleteTxtEmpNo.Text = ”
txtEmpName.Text = ”
TxtempAddr1.Text = ”
TxtempAddr2.Text = ”
TxtempAddr3.Text = ”
TxtempAddr4.Text = ”
Call prCoboBoxFill
Exit For
End If
Next i
If Trim(ComboBox1.Text) = ” Then
cmdSave.Enabled = False
cmdDelete.Enabled = False
Else
cmdSave.Enabled = True
cmdDelete.Enabled = True
End If
End If
End Sub
——————————–
Private Sub CmdClose_Click()
If CmdClose.Caption = “Close” Then
Unload Me
Else
CmdClose.Caption = “Close”
CmdNew.Enabled = True
CmdDelete.Enabled = True
End If
End Sub
————————————-Private Sub PrComboBoxFill()
TRows = Worksheets(“Data”).Range(“A1”).CurrentRegion.Rows.Count
ComboBox1.Clear
For i = 2 To TRows
ComboBox1.AddItem Worksheets(“Data”).Cells(i, 1).ValueNext i
End Sub
—————————————————–
Private Sub Userform_Initialize()
Call PrComboBoxFillCmdSave.Enabled = False
CmdDelete.Enabled = FalseEnd Sub
—————————————————–
Private Sub cmdsearch_Click()
binNew = False
txtEmpNo.Text = ”
txtEmpName.Text = ”
txtAddr1.Text = ”
txtAddr2.Text = ”
txtAddr3.Text = ”TRows = Worksheets(“Data”).Range(“A1”).CurrentRegion.Rows.Count
For i = 2 To TRows
If Val(Trim(Worksheets(“Data”).Cells(i, 1).Value)) = Val(Trim(ComboBox1.Text)) ThentxtEmpNo.Text = Worksheets(“Data”).Cells(i, 1).Value
txtEmpName.Text = Worksheets(“Data”).Cells(i, 2).Value
txtAddr1.Text = Worksheets(“Data”).Cells(i, 3).Value
txtAddr2.Text = Worksheets(“Data”).Cells(i, 4).Value
txtAddr3.Text = Worksheets(“Data”).Cells(i, 5).ValueExit For
End If
Next i
If txtEmpNo.Text = ” Then
Else
CmdSave.Enabled = True
CmdDelete.Enabled = True
End If
End Sub
Effectively Manage Your
Projects and Resources
ANALYSISTABS.COM provides free and premium project management tools, templates and dashboards for effectively managing the projects and analyzing the data.
We’re a crew of professionals expertise in Excel VBA, Business Analysis, Project Management. We’re Sharing our map to Project success with innovative tools, templates, tutorials and tips.
Project Management
Excel VBA
Download Free Excel 2007, 2010, 2013 Add-in for Creating Innovative Dashboards, Tools for Data Mining, Analysis, Visualization. Learn VBA for MS Excel, Word, PowerPoint, Access, Outlook to develop applications for retail, insurance, banking, finance, telecom, healthcare domains.
Page load link
3 Realtime VBA Projects
with Source Code!
Go to Top
One of the most commonly used features in Excel are its functions.
This is hardly surprising. After all, Excel has hundreds of built-in functions.
The variety, in terms of uses and complexity, is quite remarkable. Excel seems to have a function for everything.
But…
Is this really the case?
And…
Even assuming that there is a function for everything, is relying solely on Excel’s built-in functions the most productive way to work?
If these type of questions have ever crossed your mind, and you’ve ever wondered how you can create new functions in Excel, I’m sure you’ll find this tutorial interesting.
On the other hand, you may think that with all the functions that are available in Excel, there is absolutely no need to create new functions. If that is the case, I’m confident that you’ll still find useful information in this blog post. Additionally, I believe that the information within it may just change your opinion.
The reason why I believe that, regardless of your opinion about the need to create new functions in Excel, you’ll find this Excel tutorial interesting is that, indeed, it explains how to you can create your own custom functions (technically called VBA Function procedures). And, just in case you believe this is unnecessary, this guide also provides strong reasons why you should consider creating and using these custom VBA functions.
The main purpose of this tutorial is to introduce to you Excel VBA Function procedures, also known as custom functions, User-Defined Functions or UDFs. More precisely, after reading this Excel tutorial on Excel VBA Function procedures, you’ll know the most relevant aspects regarding the following topics:
Where relevant, every concept and explanation is illustrated with the help of a basic example.
This Excel VBA Function Procedures Tutorial is accompanied by an Excel workbook containing these examples. You can get immediate free access to this example workbook by subscribing to the Power Spreadsheets Newsletter.
Let’s start by understanding, more precisely…
What Is A Procedure: Excel VBA Function Procedures Vs. VBA Sub Procedures
In general terms, a procedure is the part of a computer program that performs a particular task or action. If you’re working with Excel’s Visual Basic Editor, a procedure is the block of statements enclosed by a declaration statement and an End declaration.
When working with Visual Basic for Applications, you’ll constantly encounter 2 types of procedures:
- Sub procedures, which carry out one or more actions in Excel.
- Sub procedures don’t require arguments and don’t return data. You’ll see below that Function procedures do both of these.
- Function procedures, which carry out a calculation and return a value (can be a number or a string) or array.
- Function procedures are passive: they generally don’t carry out any actions. There is, however, at least one exception to this rule: It is possible to change the text in a cell comment using Function procedures.
- There are other methods that, when used in a VBA function, can also make changes to a workbook. Additionally, Function procedures that aren’t used in worksheet formulas can do pretty much the same as a regular Sub procedure.
In practice, you’re likely to (mostly) work with Sub procedures. In other words: Most of the procedures you’ll create will (likely) be Sub procedures.
The reason for this is that most macros are small/brief automations. As a consequence, most macros are self-contained Sub procedures.
The fact that most macros are self-contained Sub procedures used to carry out relatively simple jobs shouldn’t stop you from creating more complex and sophisticated macros when required.
As you’ll see in this Excel tutorial, VBA Function procedures can play a key role when creating complex and sophisticated macros. Therefore, let’s take a closer look at…
What Is An Excel VBA Function Procedure
Even if you’re not very familiar with Excel, you’re probably familiar with the concept of functions.
The reason for this is that, even if you’ve never used Visual Basic for Applications, you’ve probably worked quite a bit with worksheet functions. These are the functions that you use every time you create a formula in an Excel worksheet and, as a side-note, you can also use them in VBA.
Some examples of worksheet functions are SUM, IF, IFERROR and VLOOKUP function.
Worksheet functions work very similarly to Excel VBA Function procedures. Worksheet functions (generally) proceed as follows:
- Step #1: They generally take one or more arguments. There are some exceptions to this rule, as some functions such as TRUE and FALSE take no arguments.
- Step #2: The functions carry out a particular calculation.
- Step #3: Finally, a value is returned.
Excel VBA Function procedures do exactly the same thing. In other words, VBA functions take arguments and return values.
VBA Function procedures are very versatile. You can use them both when working with Visual Basic for Applications or directly in an Excel worksheet formula. I explain both ways of executing a VBA Function procedure below.
If Excel VBA Function procedures function similarly to regular worksheet functions, you may wonder…
Why Create And Use Excel VBA Function Procedures?
Excel has hundreds of functions. These functions carry out a huge range of calculations, some more useful than others.
Considering the huge amount of available worksheet functions, you may wonder whether you should take the time to learn how to create additional functions using Visual Basic for Applications.
I hope that, after reading this Excel tutorial and getting an idea about what Excel VBA Function procedures can do for you, you’ll agree with me that it makes sense to learn about this tool and use it when appropriate. The reason is that VBA Function procedures allow you to simplify your work. More precisely: User-Defined Functions (Function procedures) are useful when working with both:
- Worksheet formulas; and
- VBA procedures.
The following are some of the advantages of using Excel VBA Function procedures:
- VBA Function procedures can help you shorten your formulas. Shorter formulas are easier to read and understand. More generally, they are easier to work with.
- When creating applications, custom functions may help you reduce duplicated code. Among other advantages, this helps you minimize errors.
- When using VBA functions, you can write functions that perform operations that would (otherwise) be impossible.
The simplicity of of Excel VBA Function procedures (once they’re created) is illustrated by the fact that, once the User-Defined Function (Function procedure) has been created, a regular user (only) needs to know the function’s:
- Name; and
- Arguments.
VBA Function procedures can be extremely helpful when creating large and complex VBA projects. The reason for this is that, when working in large projects, you’ll usually create a structure involving multiple procedures (both Sub and Function procedures).
Since VBA Functions take incoming data (arguments) and return other data (values that result from calculations), they’re very useful for purposes of helping different procedures communicate between themselves. In other words, one of the strongest reasons why you should create and use VBA Function procedures is for purposes of improving your VBA coding skills in general. Appropriately working with Function procedures and Sub procedures becomes increasingly important as the size and complexity of your VBA Applications increases.
More precisely, when creating large and complex projects, you can take advantage of the ability of VBA functions to return a value. You can (usually) do this by assigning the name of the Excel VBA Function procedure to a variable in the section of the procedure where you call the function.
I explain how to call VBA Function procedures from other procedures further below.
Basic Syntax Of An Excel VBA Function Procedure
When working with VBA Sub procedures you can, up to a certain extent, rely on Excel’s macro recorder. This allows you to create basic macros by simply carrying out and recording the actions you want the macro to record and store.
When working with Excel VBA Function procedures, you can’t use the macro recorder. In other words, you must always enter the relevant VBA code.
The macro recorder may, however, be a helpful tool for purposes of finding properties (which I explain this blog post) and methods (which I cover here) that you may want to use in the Function procedure you’re creating.
The basic elements of an Excel VBA Function procedure are the following:
- It always begins with the Function keyword.
- It always ends with the End Function statement.
- Between the declaration and End statements, it contains the relevant block of statements with instructions.
As an example, let’s take the following very simple Excel VBA Function procedure (called Squared), which simply squares a certain number which is given to it as an argument.
In practice, you’ll be working with much more complex VBA Function procedures. However, this basic function is enough for the purposes of this Excel tutorial and allows us to focus in understanding the concepts that will later allow you to build much more complicated Function procedures.
Let’s take a closer look at the first element of the sample Excel VBA Function above:
Declaration Statement Of An Excel VBA Function Procedure
As you can see in the example above, the first statement is composed of 3 items:
- The Function keyword, which declares the beginning of the VBA Function procedure.
- The name of the VBA Function procedure which, in this example, is “Squared”.
- The arguments taken by the VBA function, enclosed by parentheses. In the example above, the Squared function takes only 1 argument: number.
- If the VBA Function procedure that you’re creating takes several arguments, use a comma (,) to separate them.
- If you’re creating a function that takes no arguments, leave the parentheses empty. Note that you must always have the parentheses, even if they are empty.
- I explain the concept of arguments, in the context of Excel VBA Function procedures, in more detail below.
How To Name Excel VBA Function Procedures
The name of the VBA Function procedure appears in the declaration statement itself, as shown above.
As a general rule, Function procedure names must follow the sale rules as variable names. These rules are substantially the same as those that apply to naming naming VBA Sub procedures and, more generally, to most items or elements within the Visual Basic for Applications environment.
The following are the main rules when naming variables:
- Names must start with letters.
- As long as the name complies with the above, they can also include numbers and certain (not all) punctuation characters. For example, underscore (_) is commonly used.
- The maximum number of characters a name can have is 255.
- Names can’t be the same as any of Excel’s key words, such as “Sheet”.
- No spaces are allowed. In other words, names must be a “continuous string of characters only”.
The following are common additional suggestions for naming your VBA Function procedures:
- Don’t use function names that match a cell reference or a named range, such as A1.
- If you do this, you can’t use that particular VBA function in a worksheet formula. If you try to do it, Excel displays the #REF! error.
- Don’t use VBA Function procedure names that are the same as that of a built-in function, such as SUM.
- This causes a name conflict between functions. In such cases, Excel uses the built-in function instead of the VBA function.
You may have noticed that the names of Excel’s built-in functions are always in uppercase, such as SUM, IFERROR or AND. Some VBA users like to use uppercase names, so that they match Excel’s style. This is (however) not mandatory.
For example, I have not applied this same formatting rule in the examples that appear in this Excel tutorial, where the sample VBA functions are called “Squared”, “Squared_Sign”, “Squared_Sign_2” and “Squared_Sign”.
How To Tell An Excel VBA Function Procedure Which Value To Return
The sample Excel VBA Function above only contains one statement between the declaration statement and the End declaration statement: “Squared = number ^ 2”.
This statement simply takes a number, squares it (elevates it to the power of 2), and assigns the resulting value to the variable Squared. You’ll notice that “Squared” is also the name of this Excel VBA Function procedure.
The reason for the name of the variable matching the name of the function is that this is how you tell an Excel VBA Function procedure which value to return. You specify the value to return by assigning that value to the function’s (Function procedure’s) name.
In other words, in these cases, the name of the function also acts as a variable. Therefore, when working with Function procedures, you’ll constantly encounter the name of the function being used as the name of a variable within the Function procedure itself. You must (as a general rule) assign a value to the Function procedure’s name one time (as a minimum).
You may see this clearer when dividing the process followed by a VBA function in the following 3 steps:
- Step #1: The function carries out the relevant calculations.
- Step #2: The VBA function assigns the obtained results to its own name.
- Step #3: Once the function ends, it returns the results.
Therefore, when creating Excel VBA Function procedures, you want to ensure that the condition above is complied with. In other words, make sure that, somewhere in the main body of the VBA code, the correct value is assigned to the variable that corresponds to the function name. In the example above, the only statement of the function assigns a value to the Squared variable.
Once an Excel VBA Function procedure has carried out any intermediate calculations, it returns the final value of the variable whose name is the same as the function’s name.
In the example above, the name of the function and returned variable is “Squared”. Therefore, once the VBA Function procedure carries out the required calculations, it returns the final value of the variable Squared.
Arguments Within Excel VBA Function Procedures
Arguments are the information or data that a function uses as input to carry out calculations.
When working with Excel VBA Function procedures you’ll usually encounter arguments in the following 2 situations:
- Situation #1: When declaring an Excel VBA Function procedure, you always include a set of parentheses. This is where you include the arguments taken by the function. If the function takes no arguments at all, you leave the parentheses empty.
- The Squared VBA Function used as an example above takes only 1 argument: number.
- The Squared VBA Function used as an example above takes only 1 argument: number.
- Situation #2: When executing the VBA Function procedure, you’ll usually (although not always) enter the arguments that the function must use to carry out its calculations.
- You can see how to execute an Excel VBA Function procedure, and enter the relevant arguments, below.
The following is a list of important points to bear in mind when working with both regular worksheet functions and VBA Function procedures.
- There are several ways in which a function can receive arguments. You can use any of the following as formula arguments:
- #1: Cell references.
- #2: Variables, including arrays.
- #3: Constants.
- #4: Literal values.
- #5: Expressions.
- The number of arguments vary from function to function.
- There are functions that have absolutely no arguments, such as TRUE and FALSE.
- On the other hand, there are functions that can take a very large number of arguments. For example, functions such as AND or OR can take up to 255 arguments. This leads me to the last point…
- Arguments can be either required or optional. The number of required or optional arguments varies between functions.
- Some functions have only a fixed number of required arguments. For example, the IF function has 3 required arguments.
- Other functions combine required and optional arguments. Examples of such functions are LEFT and RIGHT, which you can use to find what the first (LEFT) or last (RIGHT) characters in a text string are.
After seeing this last point, you may now be wondering…
How To Create Excel VBA Function Procedures With Optional Arguments
You already know how to declare the arguments of an Excel VBA Function procedure by listing them within parentheses when you declare the function.
Arguments are mandatory by default. If, when calling a VBA function, you forget to input them, the function won’t be executed.
In the case of the Excel VBA Function procedure Squared, which I’ve used as an example above, the argument number is required.
In order to make an argument optional, you need to list it differently. More precisely, optional arguments are:
- Preceded by the Optional keyword. This allows Excel to understand that the particular argument is optional.
- Ideally, although not required, followed by an equal sign and the default value for the optional argument. This determines the value that the Excel VBA Function procedure uses if the optional argument is not passed on to the function.
- The default value can be a string, a constant or a constant expression.
- Always last in the list of arguments within the parentheses. Once you use the Optional keyword, all the arguments that follow it must also be optional.
Let’s take a look at an example:
When squaring a number (even if the number is negative), the result is a non-negative number. For example, you can square both –10 or 10 and, in both cases, the result is 100.
Let’s assume that, in some situations, you need a negative number. In other words, you’d like to have the ability to ask Excel to return a non-positive number, such as –100 instead of 100 (when squaring –10 or 10).
For these purposes, you can use an Excel VBA Function procedure such as the following, called “Squared_Sign”:
The VBA code of Squared_Sign shares many items that are also in code for the simpler Squared VBA Function procedure.
In fact, all of the items that appear in the VBA code of Squared also appear in the code of Squared_Sign. Take a look at the following image, which underlines them:
You already know what each of these items does. When put together, the sections that are underlined above simply take the argument (number) and square it.
There are only 2 new elements that have been added to the Squared_Sign function, as compared to the original Squared VBA Function procedure. These are the ones that give users the option to ask Excel to return a non-positive number by using an optional argument. Let’s take a closer look at them:
An alternative, although slightly more advanced, approach to the above situation involves using the IsMissing function.
The IsMissing function is particularly helpful for purposes of testing whether an optional argument has been given. In other words, IsMissing returns a logical value that indicates whether a particular Variant argument has been passed to the relevant procedure. More precisely:
- If no value is passed to IsMissing, it returns True.
- Otherwise, IsMissing returns False.
The VBA Function procedure (called Squared_Sign_2) that appears in the image below uses the IsMissing function to proceed as follows:
- Step #1: If the second argument (called negative) is False or missing, IsMissing sets the value of “negative” to its default value of False.
- If negative is False, the function returns a positive number. This is the same result obtained with the Squared VBA function.
- Step #2: If the argument called negative is True, the Squared_Sign_2 VBA function returns a negative number.
How To Create Excel VBA Function Procedures With An Indefinite Number Of Arguments
There are some built-in functions that can take an “indefinite” number of arguments.
By “indefinite”, I mean up to 255.
One example of a built-in function that accepts an indefinite number of arguments in Excel is SUM. Take a look at the following screenshot of how this looks like in the Function Arguments dialog:
You can also create VBA Function procedures that take an unlimited number (meaning up to 255) arguments. You do this as follows:
- Use an array as the last or only argument in the list of arguments that you include in the declaration statement of the VBA function.
- Use the ParamArray keyword prior to that final (or only) array argument.
When used in the context of a VBA Function procedure, ParamArray indicates that the final argument of that function is an “optional array of Variant elements”.
You can’t use ParamArray alongside other optional keywords in the argument list of a VBA Function, such as Optional, ByVal or ByRef. Therefore, you can’t use both Optional and ParamArray in the same function.
Let’s see how ParamArray works in practice by creating a function that proceeds as follows:
- Step #1: Squares (elevates to the power of 2) a particular number. This is what the (less complex) Squared VBA Function achieves.
- Step #2: Sums the squared numbers.
The following VBA Function procedure (called “Squared_Sum”) is a relatively simple way of achieving this. Notice how the arguments are declared as an optional array of elements of the Variant data type.
This Excel VBA Function procedure isn’t particularly flexible. For example, it fails if you use a range of cells as argument and 1 of the cells contains a string (instead of a number).
However, for our purposes, Squared_Sum gets the job done. It particularly illustrates how you can use the ParamArray keyword to create VBA functions with an unlimited number of arguments.
In order to test that the Squared_Sum function works as planned, I have created an array listing the integers from 1 to 100 and applied Squared_Sum to it.
In order to confirm that the result returned by Squared_Sum is correct, I manually (i) squared each of the numbers in the array and (ii) added those squared values. Check out the 2 screenshots below showing how I set up this control:
As shown in the image below, the results returned by both methods are exactly the same.
The Squared_Sum VBA function is, however, easier and faster to implement than carrying out the calculations manually or creating long and complicated nested formulas.
This Excel VBA Function Procedures Tutorial is accompanied by an Excel workbook containing the data and procedures I use in the examples above. You can get immediate free access to this example workbook by subscribing to the Power Spreadsheets Newsletter.
Other Optional Items For An Excel VBA Function Procedure
The syntax described in the sections above outlines and illustrates the basic items you should include in the VBA code of a Function procedure.
Below is a much more comprehensive syntax for declaring functions, by including all its optional elements. Let’s take a look at it:
[Public | Private] [Static] Function name ([arglist]) [As type] [instructions] [name = expression] [Exit function] [instructions] [name = expression] End Function
Notice that this structure shares many elements in common with that of a Sub procedure.
Let’s take a look at the optional elements (within brackets [ ]) that appear in the structure above.
Element #1: [Public | Private]
Private and Public are access modifiers and determine the scope of the VBA Function procedure. This means that the access modifiers are used to determine if there are any access restrictions in place.
In more practical terms, this is important because the scope of a function is what determines whether that particular VBA function can be called by VBA procedures that are stored in other modules or worksheets.
More precisely:
- Public Function procedures have no access restrictions. As a consequence, they can generally be accessed by all other VBA procedures in any module within any active Excel VBA project.
- Public is the default scope of VBA functions.
- Despite the above, Excel VBA Function procedures within a module that uses the Option Private statement, are not accessible from outside the relevant project.
- Private Function procedures are restricted. Therefore, only other VBA procedures within the same module can access them.
- Additionally, Private functions are not listed in Excel’s Insert Function dialog, which is one of the ways of calling an Excel VBA Function procedure. Knowing this is useful if you’re creating VBA functions that are designed to be called only by a Sub procedure. In that case, you can declare the relevant function as Private to reduce the probability of a user using such a function in a worksheet formula.
- Declaring an Excel VBA Function procedure as Private doesn’t fully prevent that function from being used in a worksheet formula. It simply prevents the display of the relevant function in the Insert Function dialog. I explain how you can call a VBA function using a worksheet formula below.
Element #2: [Static]
If you use the Static statement, any variables declared within the VBA Function procedure retain their values “as long as the code is running”. In other words, the values of any variables declared within the function are preserved between calls of the function.
Element #3: [arglist]
I explain the concept of arguments above.
Even though arguments are optional, meaning that you can have an Excel VBA Function procedure that takes no arguments, the set of parentheses after the Function name isn’t optional. You must always have the set of parentheses.
Element #4: [As type]
The As keyword, when combined with the Type statement, is used to determine which data type the VBA Function procedure returns.
Even though this item is optional, it’s (also) commonly recommended.
Element #5: [instructions]
Instructions are the VBA instructions that determine the calculations to be carried out by the Excel VBA Function procedure.
I mention these above as, generally, most Excel VBA Functions include some instructions.
Element #6: [name = expression]
This element makes reference to the fact that a correct value must be assigned to the variable that corresponds to the function name at least 1 time. This happens, generally, when execution of the instructions is completed.
An easy way to ensure that you’re meeting this condition is to follow the syntax “name = expression”, where:
- “name” is the name of the Excel VBA Function procedure.
- The name is followed by an equal (=) sign.
- “expression” is the value that the function should return.
Despite the above, this item is technically optional.
This topic is further explained above, where I explain how the value that a VBA function returns is determined.
Element #7: [Exit Function]
The Exit Function statement immediately exits the Function procedure.
Where To Store Excel VBA Function Procedures
There are 2 separate points that you may want to consider when storing an Excel VBA Function procedure. Let’s take a look at them:
Point #1: Always Store Excel VBA Function Procedures In Standard Modules
VBA code is generally stored in a module.
There are, however, a few different types of modules. If you put your VBA code in the wrong module, Excel isn’t able to find it or execute it.
Excel VBA Function procedures should always be stored in a standard module.
Make sure that you don’t store your Function procedures in other type of modules. If you fail to store your functions in a standard module, those formulas return the #NAME? error when executed.
The reason for this is that, when you enter a VBA Function procedure in another module, Excel doesn’t recognize that you’re creating a new VBA function.
You can refer to The Beginners Guide to Excel’s Visual Basic Editor, to see how you can insert and remove VBA modules.
As long as you meet the requirement of storing your VBA functions in standard modules, you can store several VBA Function procedures in a single module.
Point #2: Suggestions To Determine Where To Store Excel VBA Function Procedures
Consider the following guidelines to decide where to store VBA Function procedures:
- If the particular VBA function is only for your use, and won’t be used in another computer, store it in your personal macro workbook: Personal.xlsb.
- The personal macro workbook is a special type of workbook where you can store macros that are generally available when you use Excel in the same computer. This is the case, even if you’re not working on the same workbook in which you created the macro.
- If you need to distribute an Excel workbook that contains a VBA function to several people, store the function in that workbook.
- If you need to create several workbooks that use the same VBA Function procedure, and you’ll be distributing the workbooks to many people, store the function in a template.
- If you’ll be sharing a workbook with a VBA function among a determined group of people, use an add-in.
- You may also want to consider using an add-in for storing functions that you use constantly. The following are the 2 (main) advantages of using add-ins for these purposes:
- Advantage #1: Once the add-in is installed, you can use the functions in any Excel workbook.
- Advantage #2: You can, slightly, simplify your formulas whenever you’re using VBA functions that aren’t stored in the same Excel workbook you’re working in. The reason for this is that you avoid the need of having to tell Excel where is the VBA function by providing a filename qualifier. I explain the topic of such references in detail below.
- Using a add-ins, however, also carry some disadvantages. The more important disadvantage is that your Excel workbooks become dependent on the add-in file. Therefore, whenever you share a workbook that uses a VBA function stored in an add-in, you also need to share the relevant add-in.
- You may also want to consider using an add-in for storing functions that you use constantly. The following are the 2 (main) advantages of using add-ins for these purposes:
VBA Data Types And Excel VBA Function Procedures
I explain why learning and understanding the different VBA data types is important here.
At the most basic level, data types determine the way in which data is stored in the memory of a computer.
An inadequate choice or use of VBA data types usually results in an inefficient use of the memory. This inefficient use may have different effects in practice, with the most common being a slower execution of the VBA applications where data types are chosen or used incorrectly.
In the context of Excel VBA Function procedures, VBA data types are important in 2 scenarios:
- Scenario #1: An Excel VBA Function procedure can return different types of data types. You can choose which particular VBA data type is returned by a Function procedure.
- You can find an explanation of how to use the As keyword and Type statement for purposes of setting the appropriate data type above.
- You should generally make use of this option and explicitly determine the data type returned by any function.
- Scenario #2: When declaring arguments for an Excel VBA Function, you can also use the As keyword and Type statement for purposes of determining its data type.
- Some advanced VBA user argue that specifying the data type is always a good idea because it helps you conserve memory and, mainly, helps you avoid errors caused by other procedures passing the incorrect type of information to a function.
- It goes without saying that you should ensure that the data type of the argument matches the data type expected by the relevant procedure.
How To Execute An Excel VBA Function Procedure
I explain 9 ways in which you can execute a VBA Sub procedure here. The options to execute, run or call an Excel VBA Function procedure are much more restricted. In particular, you can’t execute an Excel VBA Function procedure directly by using the same methods you can use to execute a VBA Sub procedure, such as using the Macro dialog, a keyboard shortcut, or a button or other object.
You can generally only execute a Function procedure in the following 3 (broad) ways:
- Option #1: By calling it from another procedure. The calling procedure can be either a VBA Sub procedure or a VBA Function procedure.
- Option #2: By calling it from the Immediate Window of the Visual Basic Editor.
- Option #3: By using it in a formula, such as a worksheet formula or a formula used to specify conditional formatting.
Let’s take a look at how you can implement each of these options:
Option #1: How To Call An Excel VBA Function Procedure From Another Procedure
Let’s take a look again at the sample Excel VBA Function procedure called Squared:
The easiest method to call an Excel VBA Function Procedure is to simply use the function’s name. When using this particular method, you simply need to enter 2 things in the VBA code of the calling procedure:
- The name of the Excel VBA Function procedure being called.
- The argument(s) of the procedure being called.
As an example, let’s create a very simple VBA Sub procedure (named Squared_Caller) whose only purpose is to call the Squared VBA Function procedure to square the number 15 and display the result in a message box.
If you execute the above macro, Excel displays the following message box:
Let’s take a look at the process followed by the Squared_Caller Sub procedure step-by-step.
- Step #1: The Squared_Called Sub procedure is called using any of the methods that can be used to execute an Excel VBA Sub procedure.
- Step #2: The Squared_Called Sub procedure calls the Squared function procedure and passes to it the argument of 15.
- Step #3: The Squared function receives the argument of 15.
- Step #4: The Squared function performs the relevant calculation (squaring) using the value it has received as an argument. The resulting value when squaring 15 is 225.
- Step #5: The Squared function assigns the result of its calculations (225) to the variable Squared.
- Step #6: The Squared function ends and control returns to the Squared_Called Sub procedure.
- Step #7: The MsgBox function displays the value of the Squared variable which, as explained above, is 225.
Alternatively, you can use the Application.Run method. In this case, the equivalent of the Squared_Caller VBA Sub procedure that appears above, is as the following Sub procedure (called Squared_Caller_Run):
The first argument of the Application.Run method is the macro to run (Squared in the case above). The subsequent parameters (there is only 1 in the example above) are the arguments to be passed to the function being called.
The following can be arguments when using the Application.Run method:
- Strings.
- Numbers (as above).
- Expressions.
- Variables.
Option #2: How To Call An Excel VBA Function Procedure From The Immediate Window Of The Visual Basic Editor
The Immediate Window of the Visual Basic Editor is very useful for purposes of checking, testing and debugging VBA code.
The following image shows a possible way of calling the Squared VBA function from the Immediate Window:
The word Print that appears in the Immediate Window above allows you to evaluate an expression immediately. Alternatively, you can use a question mark (?), which acts as a shortcut for Print.
Option #3: How To Call An Excel VBA Function Procedure Using A Formula
You can’t execute VBA Sub procedures directly by using a worksheet formula. This is because a Sub procedure doesn’t return a value.
Executing an Excel VBA Function procedure using a worksheet formula is relatively simple, as long as you have some basic familiarity with regular worksheet functions.
In fact, working with an Excel VBA Function procedure in this way is substantially the same as working with the regular worksheet functions such as SUM, IF, IFERROR and VLOOKUP.
The main difference between built-in worksheet formulas and VBA Function procedures is that, when using VBA functions, you must make sure that (when necessary) you tell Excel the location of the function. This is the case, usually, when you’re calling Excel VBA Function procedures that are stored in a different workbook from the one you’re working on. I explain how to do this further below.
In addition to using VBA Function procedures in worksheet formulas, you can use them in formulas that specify rules for conditional formatting. When creating conditional formatting formulas, the logic is similar to that explained below.
In order to understand this, let’s take a look at 2 of the most common methods for executing a worksheet function and see how they can be applied for purposes of executing a VBA Function procedure.
Method #1: How To Enter A Formula Using A VBA Function Procedure
If you’ve worked with formulas before, you’re probably aware that you can generally execute worksheet functions by entering a formula into a cell.
You can do exactly the same with VBA Function procedures. In other words, you can execute a Function procedure by simply typing a formula in a cell. This particular formula must contain the Function procedure you want to execute. For these purposes:
- The name of the function is exactly the same name you’ve assigned to the Excel VBA Function procedure.
- The arguments, if applicable, are entered within the parentheses that follow the name of the function (just as you’d do with any other function).
As an example, let’s assume that you want to execute the sample Squared VBA Function procedure to square the number 10. For these purposes, simply type the following formula in a cell:
As expected, the result that Excel returns is the value 100.
The syntax described above only works when you’re executing Excel VBA Function procedures from the same Excel workbook as that which contains the function you’re calling, or when the function is stored in an add-in. Functions stored in add-ins are available for use in any Excel workbook.
Let’s assume, however, that you’re actually working in a different Excel workbook from the one that contains the module with the Function procedure you want to call. In these cases, you must tell Excel where it can find the VBA function you want to work with.
In such a case, you can proceed in either of the 2 following ways. This assumes that the VBA Function procedure you want to refer to is Public, and not Private.
Option #1: Include File Reference Prior To Function Name.
In this case, you must modify the syntax slightly by adding the name of the relevant workbook before the function name. When doing this, make sure that:
- You separate the worksheet and function names using an exclamation mark (!).
- The Excel workbook that contains the relevant Function procedure is open.
For example, let’s assume that the Squared VBA Function procedure above is defined in the Excel workbook Book1.xlsm. You’re working in a different Excel workbook, and want to square the number 10 using Squared. In such case, the formula that you should type is as follows:
As expected, Excel returns the value 100.
Option #2: Set Up A Reference To Appropriate Excel Workbook.
You can set up a reference to the appropriate Excel workbook using the References command of the Visual Basic Editor. You can find this in the Tools menu of the VBE.
If you choose to set up a reference to the Excel workbook where the relevant VBA Function procedure is stored, you don’t need to modify the syntax to include the file reference prior to the Function name.
Let’s take a look now at the second way in which you can call an Excel VBA Function procedure using a formula:
Method #2: How To Execute A VBA Function Procedure Using The Insert Function Dialog
You can also (generally) execute VBA Function procedures by using the Insert Function dialog. The main exception to this rule are VBA functions that are defined as Private.
Using the Private keyword is useful when you create VBA Function procedures that aren’t designed to be used in formulas. These functions are, then, generally executed by calling them from another procedure.
Let’s see how to execute a VBA function using the Insert Function dialog in the following 4 easy steps.
Step #1: Display The Insert Function dialog.
To get Excel to display the Insert Function dialog, click on “Insert Function” in the Formulas tab of the Ribbon or use the keyboard shortcut “Shift + F3”.
Step #2: Ask Excel To Display User Defined Functions.
Once you’ve clicked on “Insert Function”, Excel displays the Insert Function dialog. Functions are organized in different categories, such as Financial, Text and Logical. You can see all the categories by clicking on the Or select a category drop-down menu.
For the moment, the category we’re interested in is User Defined functions. Therefore, click on “User Defined”.
Excel VBA Function procedures appear in the list of User Defined functions by default. You can, however, change the category in which such functions appear by following the procedure that I describe below.
You can’t use the search feature at the top of the Insert Function dialog for purposes of searching VBA functions.
The following screenshot shows what happens if I search for the Squared VBA Function procedure. Notice how none of the functions that appear in the Select a function list box is the one I’m actually looking for.
Step #3: Select The Excel VBA Function Procedure To Be Executed.
Once you’ve selected User Defined functions, Excel lists all the available VBA Function procedures in the Select a function list box.
Select the function that you want to execute and click on the OK button located on the lower right corner of the Insert Function dialog.
In the example image below, there’s only 1 VBA Function procedure: Squared. Therefore, in order to execute Squared, I select it and click on the OK button, as shown in the image below.
Step #4: Insert The Arguments For The Excel VBA Function Procedure.
Once you’ve selected the Excel VBA Function procedure to be executed, Excel displays the Function Arguments dialog.
Enter the relevant argument(s) that the function should work with (if any). Once you’ve entered these arguments, click the OK button on the lower right corner of the Function Arguments dialog to complete the process.
In the case of the sample Squared VBA Function procedure, the Function Arguments dialog looks as follows. Just as in the example above (entering a formula directly on the active cell), I enter the number 10 as argument.
As expected once again, the result returned by Excel is 100, which is correct.
Despite the fact that, operationally, executing an Excel VBA Function procedure is substantially the same as executing a regular worksheet function, you may have noticed 1 key difference:
Excel usually displays a description of worksheet functions. This happens regardless of which of the 2 methods described above you use. However, the same doesn’t happen (automatically) in the case of VBA Function procedures.
Let’s take a closer look at this difference, and see how we can get Excel to display the description of any VBA Function procedure:
How To Add A Description For An Excel VBA Function Procedure
First, let’s take a look at the way in which Excel displays the descriptions of regular worksheet functions, depending on which of the 2 methods of executing functions (described above) you’re using.
Method #1: Entering A Formula On An Active Cell
If you’re entering a function on an active cell, Excel displays a list of functions that can be used to complete the formula you’re writing. Additionally, Excel displays the description of the function that is currently selected in that list.
The following image shows how Excel automatically displays a list of options while I’m typing “=sum” to help me complete the formula. Note, in particular, how Excel describes the SUM function using tooltips.
Excel also includes VBA Function procedures in its list of suggestions to complete a formula. However, it doesn’t show a description of those functions.
For example, when I type “=squared”, Excel does suggest the Squared VBA Function procedure that I’ve created. However, it doesn’t display any description.
Method #2: Using The Insert Function Dialog
A similar thing happens if you’re using the Insert Function dialog for purposes of executing a function.
As a general rule, the Insert Function dialog displays the description of the function that is currently selected in Select a function list box. You see this on the lower section of the Insert Function dialog.
For example, in the case of the SUM function, the Insert Function dialog looks roughly as follows:
However, in the case of the Squared VBA Function procedure, things look different. As you’ll notice in the image below, the Insert Function dialog states that no help is available.
In this Excel Macro Tutorial for Beginners, I explain why you should get in the habit of describing your macros. Among other benefits, this allows you and other users to be aware (always) of what a particular macro does and what to expect when running it.
This suggestion also applies to Excel VBA Function procedures. Ideally, you should always add a description for any function you create.
Therefore, let’s take a look at how you can add a description for a VBA Function procedure in Excel:
How To Add A Description For An Excel VBA Function Procedure When Using The Insert Function Dialog
You can add a description for an Excel VBA Function procedure using either of the following 2 methods.
Any description of an Excel VBA Function procedure that you add using either of these 2 methods is only displayed when working with the Insert Function dialog. In other words, this method doesn’t add a tooltip that appears when entering a formula in an active cell.
Method #1: Using The Macro Dialog
You can add a VBA function description using the Macro dialog in the following 3 simple steps.
Step #1: Open The Macro Dialog.
To open the Macro dialog, click on “Macros” in the Developer tab of the Ribbon or use the keyboard shortcut “Alt + F8”.
Excel displays the Macro dialog. You’ll notice that this dialog lists only VBA Sub procedures. Excel VBA Function procedures don’t appear.
For example, in the following screenshot, the only macro that is listed is Squared_Caller. As I explain above, this is a VBA Sub procedure whose only purpose is to call the Squared Function procedure.
Take a look at the following step to see how to work with VBA Function procedures from the Macro dialog.
Step #2: Type The Name Of The VBA Function Procedure You Want To Describe And Click On The Options Button.
Despite the fact that the Macro dialog doesn’t display Excel VBA Function procedures, you can still work with them using the Macro dialog.
For these purposes, simply enter the name of the relevant function in the Macro name field. Once you’ve entered the appropriate name, click on the Options button located on the right side of the Macro dialog.
For example, when working with the VBA function called Squared, type “Squared” and click on “Options” as shown in the image below.
Step #3: Enter A Description Of The Excel VBA Function Procedure And Click The OK Button.
After you click “Options” in the Macro dialog, Excel displays the Macro Options dialog.
Type the description you want to assign to the VBA Function in the Description box and click on the OK button on the lower right corner of the Macro Options dialog.
The following image shows how this looks like in the case of the Squared VBA Function procedure.
Step #4: Click On The Cancel Button.
Once you’ve entered the description of the Excel VBA Function procedure and clicked the OK button, Excel returns to the Macro dialog.
To complete the process of assigning a description to a VBA Function, click on the Cancel button on the lower right corner of the Macro dialog.
Notice how the Macro dialog displays (on its lower part) the new description of the Excel VBA Function procedure.
Next time you execute the Excel VBA Function using the Insert Function dialog, Excel displays the relevant description that you’ve added. For example, the following image shows how the description of the Squared function appears in the Insert Function dialog.
As mentioned at the beginning of this section, this way of adding a description to an Excel VBA Function procedure doesn’t add a tooltip when entering a formula in an active cell. For example, when entering “=squared”, Excel continues to suggest the Squared VBA Function without showing its description.
As I explain below, this issue is more complicated to solve and exceeds the scope of this Excel VBA tutorial.
Method #2: Using The Application.MacroOptions Method
You can also add a description for an Excel VBA Function procedure using VBA code. For these purposes, you use the Application.MacroOptions method.
The main use of the Application.MacroOptions method is that it allows you to work with the Macro Options dialog. As shown below, you can also use this method for purposes of changing the category of an Excel VBA Function procedure.
The Application.MacroOptions method has several optional parameters. In this particular case, I only use 1 argument: Description. As you may expect, this argument determines the description of the VBA function.
The following macro (called Function_Description) is an example of how Application.MacroOptions can be applied for purposes of adding a description for the Squared_Sign VBA Function procedure:
You only need to execute this macro once. Once the Function_Description macro has run, and you’ve saved the Excel workbook, the description you’ve assigned to the VBA function is stored for the future.
The following image shows how this description looks like in the Insert Function dialog:
However, just as with the previous method, this way of adding a description isn’t able to make Excel show a tooltip when entering a formula with the Squared_Sign function in an active cell. Notice how, in the image below, Excel doesn’t display any description for this particular VBA function:
You may be wondering:
Is there a way to make Excel display a description of a VBA Function procedure when entering a formula in an active cell?
Let’s take a brief look at this topic:
The Issue Of Adding A Description For An Excel VBA Function Procedure When Entering A Formula
Let’s go back to the question above:
Is it possible to add a description for an Excel VBA Function procedure that will be displayed when entering a formula in an active cell?
The short answer is no. Currently you can’t add a tooltip for an Excel VBA Function procedure such as those that appear when working with the standard worksheet functions. This may change in the future.
The longer answer is more complicated. The topic of adding a description for an Excel VBA Function procedure when entering a formula has been the subject of several discussions.
The way I usually handle the lack of a function description when entering formulas with Excel VBA Function procedures is by using the keyboard shortcut “Shift + Ctrl + A” to get Excel to display all the arguments of the function.
You can implement this workaround in the following 2 easy steps.
Step #1: Type The Formula With The Name Of The Relevant Excel VBA Function Procedure
This is self-explanatory. Simply type a formula as you’d usually do.
For example, if working with the Squared VBA Function procedure, simply type “=squared”.
Step #2: Press The Keyboard Shortcut “Ctrl + Shift + A”
Once you’ve typed the name of the relevant Excel VBA Function, use the keyboard shortcut “Ctrl + Shift + A”.
Once you do this, Excel displays all the arguments of the Excel VBA Function procedure in order to help you complete the formula. For example, in the case of the Squared function, Excel displays the following:
Even though this isn’t exactly the same as having Excel display a description of the VBA Function procedure, getting all the arguments of the function may help you understand what the function does. This is particularly true if both the function and the arguments have descriptive and meaningful names.
For example, if Excel displays “=squared(number)” as in the screenshot above, you’ll probably be able to figure out that the purpose of that particular VBA Function procedure is to square the number that is given as an argument.
If you’re not able to figure out what the function does using this method, you can always go to the Insert Function dialog where the description of the Excel VBA Function you’ve added always appears.
Now that we’re talking about function arguments, did you know that you can also add argument descriptions for your Excel VBA Function procedures?
Let’s take a look at how you can do this:
How To Add Descriptions For The Arguments Of An Excel VBA Function Procedure
When you use the Insert Function and Function Arguments dialogs to enter a built-in function, Excel displays a description for each of the arguments. For example, in the case of the SUM function, this looks as follows:
However, Excel doesn’t show (by default) descriptions of the arguments for an Excel VBA Function procedure. For example, the description for the arguments of the Squared function within the Function Arguments dialog looks (by default) as follows:
This is very similar to what happens with the description of the function itself, as described in the section above. And just as you can add a description for the whole Excel VBA Function procedure, you can add a description for its arguments.
The possibility of adding argument descriptions for Excel VBA Function procedures was only added in Excel 2010. If you use an earlier version of Excel, argument descriptions are not displayed.
You add descriptions for the arguments of an Excel VBA Function procedure using the Application.MacroOptions method. This method allows you to work with the Macro Options dialog.
Let’s see how you can use the Application.MacroOptions method to add a description for the arguments of a VBA Function procedure. The following macro (Argument_Descriptions) adds a description to the only argument of the Squared VBA Function.
Once you’ve run this macro once and save the Excel workbook, the argument description is stored and associated with the relevant VBA Function procedure.
Let’s go once more to the Function Arguments dialog for the Squared VBA Function. The following screenshot shows how, now, the argument has a description (is the number to be squared).
You can use macros that are similar to the Argument_Descriptions macro that appears above for purposes of adding argument descriptions to any Excel VBA Function procedure you create. The macro has only one statement containing the following 3 items:
Item #1: Application.MacroOptions method.
This is simply the Application.MacroOptions method, which allows you to work on the Macro Options dialog box. In this particular case, the Application.MacroOptions method uses the 2 parameters that appear below (Macro and ArgumentDescriptions).
Item #2: Macro Parameter.
The Macro parameter of the Application.MacroOptions method is simply the name of the Excel VBA Function procedure you want to assign an argument description to.
In the example above, this is “Squared”.
Item #3: ArgumentDescriptions Parameter.
The ArgumentDescriptions parameter is an array where you include the descriptions of the arguments for the Excel VBA Function procedure that you’ve created. These are the descriptions that, once the macro has been executed, appear in the Function Arguments dialog.
You must always use the Array function when assigning argument descriptions. This applies even if, as in the case above, you’re assigning a description for a single argument.
In the case that appears above, there is only one argument description: “Number to be squared”. If you want or need to add more than one argument, use a comma to separate them.
How To Change The Category Of An Excel VBA Function Procedure
You’ve already seen that when you create an Excel VBA Function procedure, Excel lists it by default in the User Defined category. Check out, for example, the following screenshot of the Insert Function dialog. Notice how both the Squared and the Squared_Sign VBA Function procedures appear as User Defined functions.
You may, however, want to have your VBA functions listed in a different category. That may make more sense, depending on the function that you’ve created and how are you planning to use it.
After all, the Excel Function Library has several different categories other than User Defined.
In the case of the Squared VBA Function procedure that appears in the screenshot above, it makes sense to list it under the Math & Trig category. To do this, you just need to run the following macro (named Function_Category) one time:
Once you’ve executed this macro and saved the Excel workbook with the Squared VBA Function procedure, Squared is assigned permanently to the category 3, which is Math & Trig. You can see how this looks in the Insert Function dialog:
Additionally, you can also see the Squared VBA Function procedure in the Math & Trig category in the Formulas tab of the Ribbon:
You can apply similar macros for purposes of organizing any other Excel VBA Function procedures you may have created. You just need to adjust the VBA code that appears above accordingly. Let’s take a look at this code so you understand how it proceeds and how you should use it.
The Function_Category Sub procedure contains a single statement, with the following 3 main items:
Item #1: Application.MacroOptions Method
You can use the Application.MacroOptions method, among others, for purposes of determining in which category an Excel VBA Function procedure is displayed. In the case above, the Application.MacroOptions method has only 2 parameters (Macro and Category).
Item #2: Macro Parameter
You’ve already seen the Macro parameter being used in the Application.MacroOptions method when assigning a description to a VBA Function procedure or its arguments. This parameter is simply the name of the VBA Function you want to assign a category to.
In the case above, this is Squared.
Item #3: Category Parameter
The Category parameter of the Application.MacroOptions method is an integer that determines the relevant function category. In other words, this parameter determines in which category the Excel VBA Function procedure appears.
In the example above, this is 3. However, as of the time of writing, Excel has the following 18 built-in categories.
- Financial.
- Date & Time.
- Math & Trig.
- Statistical.
- Lookup & Reference.
- Database.
- Text.
- Logical.
- Information.
- Commands.
- Customizing.
- Macro Control.
- DDE/External.
- User Defined.
- Engineering.
- Cube.
- Compatibility (introduced in Excel 2010).
- Web (introduced in Excel 2013).
In addition to the built-in categories listed above, you can create custom categories. Let’s take a look at one of the ways in which you can assign an Excel VBA Function procedure to a new custom category…
How To Create New Categories For Excel VBA Function Procedures
There are several methods to create custom categories for Excel VBA Function procedures. I may cover them in a future tutorial. If you want to be informed whenever I publish new blog posts or Excel tutorials, please make sure to register below:
In this particular section, I explain a simple way of defining a new category using the same Application.MacroOptions method described above.
When using this method, you simply replace the category parameter of the Application.MacroOptions method (3 in the example above) with a string containing the name of the new category. Let’s see how this looks in practice:
In the section above, you’ve assigned the Squared VBA Function to the Math & Trig category. However, the Squared_Sign function continues to be listed in the User Defined category.
Let’s assume that you want to list this particular VBA Function procedure under a new category named “Useful Excel Functions”. The macro that appears below achieves this. Notice how the only things that change, when compared with the Function_Category macro used above, are the parameter values, namely the name of the macro and the function category.
Once you’ve executed this macro one time and saved the relevant Excel workbook, the Squared_Sign VBA Function is assigned permanently to the Useful Excel Functions list. The reason why this works is that, if you use a category name that has never been used, Excel simply defines a new category using that name.
The result of executing the macro above looks as follows in the Insert Function dialog:
You may be wondering:
What happens if, when using the Application.MacroOptions method, you include a category name that is exactly the same as that of a built-in category?
For example, let’s go back to the Function_Category Sub procedure used to assign the Squared VBA Function to the Math & Trig category. Let’s change the integer representing the Math & Trig category (3) by the string “Math & Trig”, as shown in the image below:
As shown in the screenshot below, Excel simply lists the relevant VBA Function in the Math & Trig built-in category. No new categories are defined.
In other words, both using (i) the integer 3 or (ii) the string “Math & Trig”, as category parameter when using the Applications.MacroOptions method yield the same result: the function is assigned to the Math & Trig list (category #3).
More generally, whenever you use a category name that matches a built-in category name (such as Financial, Logical, Text, or Date & Time), Excel simply lists the relevant VBA Function procedure in that built-in category.
Conclusion
By now, you probably have a very good grasp of Excel VBA Function procedures and are ready to start creating some custom functions. However, the knowledge you’ve gained from this Excel tutorial isn’t limited to this…
You’ve also seen how you can add descriptions and organize the VBA functions you create for purposes of making their use easier later, both for you and for the people you share your Excel workbooks with.
Finally, I hope that, if you’re not yet convinced of the usefulness of Excel VBA Function procedures, you’ve found the arguments in favor of using them compelling. Hopefully, you’ll give it a try soon.
Содержание
- Calling Sub and Function procedures
- Call Sub procedures with more than one argument
- Use parentheses when calling function procedures
- Pass named arguments
- See also
- Support and feedback
- Использование функций листов Excel в Visual Basic
- Вызов функции листа из Visual Basic
- Вставка функции листа в ячейку
- Пример
- См. также
- Поддержка и обратная связь
- VBA code to call a function
- VBA Reference
- 120+ Project Management Templates
- Calling a function Excel VBA
- Calling a function Excel VBA: Function with Parameters
- Calling a user defined Function Excel VBA
- VBA code to Convert and Save the Excel to CSV – Instructions
- One Comment
- VBA Worksheet Functions: 5 Ways To Easily Use Excel Functions In VBA
- What Is A Function And What Is An Excel Worksheet Function
- How To Use Excel Worksheet Functions In VBA
- Simplification #1: Delete The Reference To The Application Object
- Simplification #2: Delete The Reference To The Application.WorksheetFunction Property
- Should You Simplify Your References To Excel Worksheet Functions In VBA?
- How To Enter An Excel Worksheet Function In VBA
- Strategy #1: Use The Insert Function Dialog Box To Identify Excel Worksheet Functions And The Function Arguments Dialog Box To Obtain Argument Descriptions
- Step #1: Open The Insert Function Dialog Box
- Step #2: Search For Excel Worksheet Function Or Select Appropriate Function Category
- Step #3: Select Excel Worksheet Function
- Step #4: Open The Function Arguments Dialog Box
- Strategy #2: Copy The Syntax Of A Worksheet Formula
- Step #1: Start Typing A Worksheet Formula Using The Excel Worksheet Function You Want To Explore
- Step #2: Press “Ctrl + Shift + A”
- Step #3: Copy The Worksheet Formula
- Step #4: Paste The Worksheet Formula As A Comment In The Visual Basic Editor
- An Alternative To Strategy #2
- Step #1: Type The Full Worksheet Formula You Want To Work With
- Step #2: Repeat Steps #3 And #4 Of Strategy #2
- Strategy #3: Use Auto List Members To Obtain A List Of Excel Worksheet Functions And Auto Quick Info To Get The Syntax Of A Function
- Strategy #4: Use The Object Browser To Browse Through The Methods Of The WorksheetFunction Object
- Step #1: Open The Object Browser
- Step #2: Select The Excel Library
- Step #3: Select The WorksheetFunction Object
- Strategy #5: Use Microsoft’s Online Help System To Get Information About A Particular Excel Worksheet Function
- Step #1: Enter The Name Of An Excel Worksheet Function
- Step #2: Place The Cursor On The Name Of The Function
- Step #3: Press The F1 Key
- What Happens When An Excel Worksheet Function Can’t Be Used In VBA
- Strategy #1: Use Auto List Members To Obtain a List Of Built-In VBA Functions
- Strategy #2: Use The Object Browser To Browse Members Of The VBA Library
- Strategy #3: Use Microsoft’s Official Documentation To Find VBA Built-In Functions
- Conclusion
Calling Sub and Function procedures
To call a Sub procedure from another procedure, type the name of the procedure and include values for any required arguments. The Call statement is not required, but if you use it, you must enclose any arguments in parentheses.
Use a Sub procedure to organize other procedures so they are easier to understand and debug. In the following example, the Sub procedure Main calls the Sub procedure MultiBeep , passing the value 56 for its argument.
After MultiBeep runs, control returns to Main , and Main calls the Sub procedure Message . Message displays a message box; when the user clicks OK, control returns to Main , and Main finishes.
Interested in developing solutions that extend the Office experience across multiple platforms? Check out the new Office Add-ins model. Office Add-ins have a small footprint compared to VSTO Add-ins and solutions, and you can build them by using almost any web programming technology, such as HTML5, JavaScript, CSS3, and XML.
Call Sub procedures with more than one argument
The following example shows two ways to call a Sub procedure with more than one argument. The second time it is called, parentheses are required around the arguments because the Call statement is used.
Use parentheses when calling function procedures
To use the return value of a function, assign the function to a variable and enclose the arguments in parentheses, as shown in the following example.
If you are not interested in the return value of a function, you can call a function the same way you call a Sub procedure. Omit the parentheses, list the arguments, and don’t assign the function to a variable, as shown in the following example.
If you include parentheses in the preceding example, the statement causes a syntax error.
Pass named arguments
A statement in a Sub or Function procedure can pass values to called procedures by using named arguments. You can list named arguments in any order. A named argument consists of the name of the argument followed by a colon and an equal sign (:=), and the value assigned to the argument.
The following example calls the MsgBox function by using named arguments with no return value.
The following example calls the MsgBox function by using named arguments. The return value is assigned to the variable.
See also
Support and feedback
Have questions or feedback about Office VBA or this documentation? Please see Office VBA support and feedback for guidance about the ways you can receive support and provide feedback.
Источник
Использование функций листов Excel в Visual Basic
В операторах Visual Basic можно использовать большинство функций листов Microsoft Excel. Список функций листов, которые можно использовать, см. в статье Список функций листов, доступных для Visual Basic.
Некоторые функции листов не используются в Visual Basic. Например, не требуется функция Concatenate, так как в Visual Basic можно использовать оператор & для объединения нескольких текстовых значений.
Вызов функции листа из Visual Basic
В Visual Basic функции листов Excel доступны через объект WorksheetFunction.
В следующей процедуре Sub используется функция листа Min для определения наименьшего значения в диапазоне ячеек. Сначала переменная myRange объявляется как объект Range, а затем ей присваивается диапазон A1:C10 на листе Sheet1. Другой переменной, answer , назначается результат применения функции Min к myRange . В конце значение answer отображается в окне сообщения.
Если вы используете функцию листа, для которой требуется ссылка на диапазон в качестве аргумента, необходимо указать объект Range. Например, можно использовать функцию листа Match (ПОИСКПОЗ) для поиска диапазона ячеек. В ячейке листа потребовалось бы ввести формулу, например =ПОИСКПОЗ (9;A1:A10;0). Однако в процедуре Visual Basic необходимо указать объект Range, чтобы получить такой же результат.
Функции Visual Basic не используют квалификатор WorksheetFunction. Функция может иметь такое же имя, что и функция Microsoft Excel, но работать по-другому. Например, Application.WorksheetFunction.Log и Log возвращают разные значения.
Вставка функции листа в ячейку
Чтобы вставить функцию листа в ячейку, укажите функцию в качестве значения свойства Formula соответствующего объекта Range. В следующем примере функция листа RAND (создающая случайное число), назначается свойству Formula диапазона A1:B3 на листе Sheet1 в активной книге.
Пример
В этом примере используется функция листа Pmt, чтобы рассчитать кредитный платеж по ипотечной ссуде. Обратите внимание, что в этом примере используется метод InputBox вместо функции InputBox, чтобы метод мог выполнять проверку типов. Операторы Static приводят к тому, что Visual Basic сохраняет значения трех переменных; они отображаются как значения по умолчанию при следующем запуске программы.
См. также
Поддержка и обратная связь
Есть вопросы или отзывы, касающиеся Office VBA или этой статьи? Руководство по другим способам получения поддержки и отправки отзывов см. в статье Поддержка Office VBA и обратная связь.
Источник
VBA code to call a function
VBA Reference
Effortlessly
Manage Your Projects
120+ Project Management Templates
Seamlessly manage your projects with our powerful & multi-purpose templates for project management.
120+ PM Templates Includes:
50+ Excel Templates
50+ PowerPoint Templates
25+ Word Templates
A Powerful & Multi-purpose Templates for project management. Now seamlessly manage your projects, tasks, meetings, presentations, teams, customers, stakeholders and time. This page describes all the amazing new features and options that come with our premium templates.
Save Up to 85% LIMITED TIME OFFER
All-in-One Pack
120+ Project Management Templates
Essential Pack
50+ Project Management Templates
Excel Pack
50+ Excel PM Templates
PowerPoint Pack
50+ Excel PM Templates
MS Word Pack
25+ Word PM Templates
Ultimate Project Management Template
Ultimate Resource Management Template
Project Portfolio Management Templates
The below example will help you to know how to call a function in Excel VBA Macros (it can be Excel VBA function, or user defined function). We generally create lot of function and we use the functions whenever and any time we want. The below example will help you to understand calling a simple function with and without parameters.
Calling a function Excel VBA
Here is the simple example to call the Now function to display the time. We use the Now function to get the System Current Time and Date.
Calling a function Excel VBA: Function with Parameters
Here is the another example to call the Left function to extract the left part of a string. We use the left function to extract the left part of any string.
Calling a user defined Function Excel VBA
It is same as above, but we have to make sure that the functions is written before calling the function. Other wise it will though the run time error.
VBA code to Convert and Save the Excel to CSV – Instructions
Please follow the below step by step instructions to test this Example VBA Macro codes:
- Step 1: Open a New Excel workbook
- Step 2: Press Alt+F11 – This will open the VBA Editor (alternatively, you can open it from Developer Tab in Excel Ribbon)
- Step 3: Insert a code module from then insert menu of the VBE
- Step 4: Copy the above code and paste in the code module which have inserted in the above step
- Step 5: Now press F8 to debug the Macro to check how the VBA is calling the function while execution
A Powerful & Multi-purpose Templates for project management. Now seamlessly manage your projects, tasks, meetings, presentations, teams, customers, stakeholders and time. This page describes all the amazing new features and options that come with our premium templates.
Save Up to 85% LIMITED TIME OFFER
All-in-One Pack
120+ Project Management Templates
Essential Pack
50+ Project Management Templates
Excel Pack
50+ Excel PM Templates
PowerPoint Pack
50+ Excel PM Templates
MS Word Pack
25+ Word PM Templates
Ultimate Project Management Template
Ultimate Resource Management Template
Project Portfolio Management Templates
Timer vba codes
Dim binNew As Boolean
Dim TRows, THows, i As Long
Private Sub UserForm_Click()
Private Sub CmdClose_Click()
If CmdClose.Caption = “Close” Then
Unload Me
Else
CmdClose.Caption = “Close”
CmdNew.Enabled = True
CmdDelete.Enabled = True
End If
End Sub
Private Sub CmdNew_Click()
binNew = True
txtEmpNo.Text = ”
txtEmpName.Text = ”
txtAddr1.Text = ”
txtAddr2.Text = ”
txtAddr3.Text = ”
CmdClose.Caption = “Cancel”
CmdNew.Enabled = False
CmdSave.Enabled = True
CmdDelete.Enabled = False
End Sub
Private Sub cmdSave_Click()
If Trim(txtEmpNo.Text) = ” Then
MsgBox “Enter Emp. No. “, vbCritical, “Save”
Exit Sub
End If
Call prSave
End Sub
Private Sub prSave()
If binNew = True Then
THows = Worksheets(“Data”).Range(“A1”).CurrentRegion.Rows.Count
With Worksheets(“Data”).Range(“A1″)
.Offset(THows, 0).Value = txtEmpNo.Text
.Offset(THows, 1).Value = txtEmpName.Text
.Offset(THows, 2).Value = txtAddr1.Text
.Offset(THows, 3).Value = txtAddr2.Text
.Offset(THows, 4).Value = txtAddr3.Text
End With
txtEmpNo.Text = ”
txtEmpName.Text = ”
txtAddr1.Text = ”
txtAddr2.Text = ”
txtAddr3.Text = ”
Call PrComboBoxFill
Else
For i = 2 To TRows
If Trim(Worksheets(“Data”).Cells(i, 1).Value) = Trim(ComboBox1.Text) Then
Worksheets(“Data”).Cells(i, 1).Value = txtEmpNo.Text
Worksheets(“Data”).Cells(i, 2).Value = txtEmpName.Text
Worksheets(“Data”).Cells(i, 3).Value = txtAddr1.Text
Worksheets(“Data”).Cells(i, 4).Value = txtAddr2.Text
Worksheets(“Data”).Cells(i, 5).Value = txtAddr3.Text
txtEmpNo.Text = ”
txtEmpName.Text = ”
txtAddr1.Text = ”
txtAddr2.Text = ”
txtAddr3.Text = ”
Exit For
End If
Next i
End If
binNew = False
End Sub
————————————-
Private Sub cmdDelete_Click()
TRows = Worksheets(“Data”).Range(“A1”).CurrentRegion.Rows.Count
Dim strDel
strDel = MagBox(“Delete ?”, vbYesNo, “Delete”)
If strDel = vbYes Then
For i = 2 To TRows
If Trims(Worksheets(“Data”).Cells(i, 1).Value) = Trim(ComboBox1.Text) Then
‘ sheet1.range(i & “:” & i).Delete
Worksheets(“Data”).Range(i & “:” & i).Delete
TxtEmpNo.Text = ”
txtEmpName.Text = ”
TxtempAddr1.Text = ”
TxtempAddr2.Text = ”
TxtempAddr3.Text = ”
TxtempAddr4.Text = ”
Call prCoboBoxFill
Exit For
End If
Next i
If Trim(ComboBox1.Text) = ” Then
cmdSave.Enabled = False
cmdDelete.Enabled = False
Else
cmdSave.Enabled = True
cmdDelete.Enabled = True
End If
End If
End Sub
——————————–
Private Sub CmdClose_Click()
If CmdClose.Caption = “Close” Then
Unload Me
Else
CmdClose.Caption = “Close”
CmdNew.Enabled = True
CmdDelete.Enabled = True
End If
End Sub
————————————-
Private Sub PrComboBoxFill()
TRows = Worksheets(“Data”).Range(“A1”).CurrentRegion.Rows.Count
ComboBox1.Clear
For i = 2 To TRows
ComboBox1.AddItem Worksheets(“Data”).Cells(i, 1).Value
Next i
End Sub
—————————————————–
Private Sub Userform_Initialize()
Call PrComboBoxFill
Источник
VBA Worksheet Functions: 5 Ways To Easily Use Excel Functions In VBA
If you’ve used Excel in the past, you’re likely familiar with worksheet functions. After all, most Excel users work with Excel worksheet functions (for ex., when creating worksheet formulas).
In this particular Excel tutorial, I focus on how you can use your knowledge of Excel worksheet functions when working with VBA.
Yes! You can use worksheet functions when writing VBA code.
In fact, the use of worksheet functions allows your VBA applications to achieve amazing results while sparing you some coding.
Additionally, as also explained at ozgrid.com, Excel worksheet functions are generally faster than a piece of VBA code written to achieve the same results. Therefore, having a good knowledge of how to use worksheet functions in VBA can help you create faster VBA applications than you’d be able to craft without them.
Therefore, my purpose with this guide is to cover all the aspects you need to understand to start using Excel worksheet functions in VBA now. The following table of contents shows the specific topics that I cover in this blog post:
Table of Contents
Let’s dive right into the topic of Excel worksheet functions in VBA by understanding…
What Is A Function And What Is An Excel Worksheet Function
As mentioned above, you can write VBA statements that use functions. You can use 3 types of functions:
- Excel worksheet functions. This is the main topic of this Excel tutorial.
- VBA built-in functions. I write about this topic briefly below, but it’s not the main focus of this tutorial.
- Function procedures. I explain how you can create and work with VBA Function procedures in this tutorial.
By the end of this blog post, you’ll have a very clear idea of what are worksheet functions, why you should use them when creating VBA applications, and how you can work with them within Visual Basic for Applications.
However, regardless of which of type of function you use, they all share the basic same fundamental purpose:
- The user (you) feeds data to the function.
- The function:
- Carries out calculations.
- Returns values.
- The user (you) can use the function’s output in the VBA code.
In other words, functions (generally):
Excel worksheet functions, which are the focus of this blog post, are provided by Excel. In other words, worksheet functions are the ones you generally use when writing formulas. You can explore and find most of these Excel worksheet functions by using the different commands and menus that appear within the Function Library in the Formulas tab of the Ribbon.
The source of worksheet functions (Excel) distinguishes this type of functions from both of the other types. More precisely:
- VBA built-in functions are provided from within the Visual Basic for Applications environment.
- Function procedures are custom or user-defined functions that you can create using VBA.
The ability to use worksheet functions in VBA gives you immediate access to hundreds of different functions that you can call from within your VBA code. You can use most, but not all, Excel worksheet functions in VBA. As a general rule, the worksheet functions not available in VBA are those with an equivalent:
- VBA built-in function; or
- VBA operator.
You can find a complete list of Excel VBA worksheet functions in Microsoft’s Official Documentation.
How To Use Excel Worksheet Functions In VBA
In order to call Excel worksheet functions using VBA, you use the WorksheetFunction object. The WorksheetFunction object is contained within the Application object.
The worksheet functions themselves are methods of the WorksheetFunction object. You can find a complete list of all the members (including methods) of the WorksheetFunction object in Microsoft’s Official Documentation.
Let’s take a look at a real example in order to understand how this works in practice. Imagine that you’re in the process of closing the yearly account of your company. Your accountant sends you the following table listing the monthly revenue:
You want to know what the lowest monthly revenue for that particular year was. For these purposes, you can generally use the MIN worksheet function. When applied to a particular set of values (such as the monthly revenues displayed in the second column above) MIN returns the smallest number.
However, let’s assume that you don’t want to use a regular worksheet formula. You’d rather have a message box display what the lowest monthly revenue was. You can do this by using the following macro (called Find_Minimum) which calls the Min worksheet function in VBA for purposes of finding the smallest monthly revenue number.
This Excel VBA Worksheet Functions Tutorial is accompanied by an Excel workbook containing the data and macros I use (including the table and macro displayed above). You can get immediate free access to this example workbook by subscribing to the Power Spreadsheets Newsletter.
When I execute the Find_Minimum Sub procedure, Excel displays the following message box:
This message box, indeed, displays the smallest monthly revenue from within the table above. You can go back to the table listing the monthly revenue and find that the month of April had lowest monthly revenue of $21,749.00. This is the value displayed in the message box.
For purposes of this Excel tutorial, we’ll focus on the VBA statement that calls the Min worksheet function. This statement is the following:
The following screenshot shows its location within the VBA code:
Let’s take a closer look at the structure of this statement:
- Item #1: Application.WorksheetFunction returns the WorksheetFunction object. As explained above, this is the object you must use in order to use Excel worksheet functions in VBA.
- More precisely, this statement uses the Application.WorksheetFunction property to return the WorksheetFunction object. This section of the statement uses the basic structure to create fully qualified object references in Visual Basic for Applications.
- Item #2: The WorksheetFunction.Min method returns the smallest value in a set of values. In other words, this is the equivalent of the MIN worksheet function.
- This part of the statement follows the basic structure you must use to work with object methods in VBA.
You can actually simplify the first item above in either of the 2 following ways. Note that these simplifications are exclusive: you can only use one or the other. You can’t use both at the same time.
Simplification #1: Delete The Reference To The Application Object
In other words, replace “Application.WorksheetFunction.Min(my_Range)” with the following:
This simplification relies on the fact that the Application object is always assumed, as I explain here.
Simplification #2: Delete The Reference To The Application.WorksheetFunction Property
- Omit the explicit reference to the WorksheetFunction property/object; and
- Call an Excel worksheet function directly through the Application object.
If you choose this simplification method, the statement “Application.WorksheetFunction.Min(my_Range)” becomes:
Should You Simplify Your References To Excel Worksheet Functions In VBA?
As a general matter, the first simplification above (omit the Application object) is clearer. As I explain in this Excel tutorial, referencing VBA properties explicitly is a good programming practice.
Explicitly referring to the WorksheetFunction property/object:
- Tends to result in VBA code that’s easier to:
- Read;
- Follow;
- Understand; and
- Work with.
- Helps make clear that you’re working with a worksheet function.
An additional advantage of using WorksheetFunction is the possibility of relying on the Auto List Members option of the Visual Basic Editor, as I explain below. If you omit the reference to WorksheetFunction, the VBE doesn’t auto list members.
However, omitting the explicit reference to the WorksheetFunction property/object (and referring explicitly to the Application object) has important advantages in terms of error handling.
More precisely: When omitting the WorksheetFunction property/object and declaring the result variable as of the Variant data type, an error is held by the variable. Therefore:
- There is no run-time error; and
- The code doesn’t stop to go into debugging mode (as it usually does in such situations).
A second (but less meaningful) advantage of calling Excel worksheet functions directly through the Application object has to do with code length and readability. More precisely, since WorksheetFunction is a relatively long word, omitting it makes the lines of code shorter.
How To Enter An Excel Worksheet Function In VBA
If you’ve read other posts in Power Spreadsheets, you probably have a good idea of how to enter worksheet functions in VBA. Even if you don’t, the general rule for inserting Excel worksheet functions is quite simple:
Type the worksheet function following the syntax rules explained in the section above.
- Can’t use Excel’s Insert Function dialog to enter worksheet functions into VBA.
- Can (however) take advantage of the following strategies to get some help when setting up the code to call a worksheet function in VBA:
Strategy #1: Use The Insert Function Dialog Box To Identify Excel Worksheet Functions And The Function Arguments Dialog Box To Obtain Argument Descriptions
Excel has hundreds of worksheet functions and, in some cases, you may not be absolutely sure about which one to use in your VBA code. In such cases, you can use the Insert Function dialog box for purposes of finding out which function can help you.
In fact, you can also use this process for purposes of understanding the arguments of a particular worksheet function.
In order to get some help from the Insert Function dialog box to identify Excel worksheet functions and learn about their arguments, follow these 4 easy steps:
Step #1: Open The Insert Function Dialog Box
You can get Excel to display the Insert Function dialog box in any of the following 2 ways:
- Click on “Insert Function” within the Formulas tab of the Ribbon.
- Use the keyboard shortcut “Shift + F3”.
Step #2: Search For Excel Worksheet Function Or Select Appropriate Function Category
Once Excel displays the Insert Function dialog box, you can find the worksheet function you need in either of the following ways:
Step #3: Select Excel Worksheet Function
Excel displays the actual worksheet functions within the Select a function box on the lower part of the Insert Function dialog box. Once you select a function, Excel describes what the function does on the lower section of the Insert Function dialog box.
For example, if I search for the term “smallest” (as suggested above), the Insert Function dialog looks as follows. Notice that the MIN function is third in the Select a function box. Also, check out the description that appears below the Select a function box.
These first 3 steps are usually enough to identify an Excel worksheet function you want to use in VBA. The fourth step below is useful if you want to learn more about the arguments of that particular function.
Step #4: Open The Function Arguments Dialog Box
You can open the Function Arguments dialog box for a particular function by either (i) double-clicking on it while in the Insert Function dialog box, or (ii) selecting it and clicking on the OK button on the lower-right corner of the Insert Function dialog box.
Once you’ve completed this step, Excel displays the Function Arguments dialog box. You can find a description of a particular argument by placing the cursor in the relevant cell. The actual description is displayed on the lower-right side of the dialog box. For example, the following screenshot shows the description of the Number1 argument of the MIN function:
The reason why this may be useful is because the argument descriptions provided by the Function Arguments dialog box are much more helpful than what is displayed by the Visual Basic Editor. As an example, compare the image above with the screenshot of the VBE shown below.
- Arguments within the Visual Basic Editor don’t have very meaningful names. For example, in the case above you go from Number1, Number2, … (in the Function Arguments dialog box) to Arg1, Arg2, … (in the Visual Basic Editor).
- The VBE doesn’t show any description for the arguments of the Min function.
Therefore, the Excel worksheet function itself provides valuable information about the syntax you should use when calling that particular function in VBA. The syntax in both cases (the worksheet function itself and the call within VBA) is substantially similar. In particular, both the number of arguments and their meanings is generally the same in both cases.
The following strategy also takes advantage of the similarities in the syntax of functions in Excel and VBA:
Strategy #2: Copy The Syntax Of A Worksheet Formula
An alternative to using the Function Arguments dialog box to get a better idea about the syntax and arguments of a particular worksheet function is to proceed as follows:
Step #1: Start Typing A Worksheet Formula Using The Excel Worksheet Function You Want To Explore
Worksheet formulas within Excel are preceded by an equal sign (=). If you’re using this method, make sure that you:
- Type the full name of the relevant Excel worksheet function.
- Place the insertion point/cursor to the right of the function name.
For example, in the case of the MIN worksheet function you’d type “=MIN”. This is shown in the image below. Notice the location of the cursor.
Step #2: Press “Ctrl + Shift + A”
Once you’re standing to the right of the worksheet function’s name, use the keyboard shortcut “Ctrl + Shift + A” to insert the function arguments.
After using this shortcut, the MIN function looks as follows:
Step #3: Copy The Worksheet Formula
Select the whole worksheet formula and copy it by, for example, using the “Ctrl + C” keyboard shortcut. You can find a comprehensive list of keyboard shortcuts here.
When copying the formula, you can exclude (not copy) the equal (=) sign. What’s more relevant is the rest of the formula which shows the syntax of the worksheet function you’re using in VBA.
Once you’ve copied the worksheet formula you’ll be using as guidance, go back to the VBE.
Once you’re back in the Visual Basic Editor environment, paste the formula you’ve copied as a comment. Comments must be preceded by an apostrophe (‘).
You can consider pasting the formula at the top of the relevant procedure. This is shown in the image below. However, this particular location isn’t mandatory. You can place the comment on another row, depending on your commenting practices.
Notice how, now, you have some clearer guidance about the arguments of that particular function. You can now simply follow that syntax when typing in the worksheet function in the VBA code.
An Alternative To Strategy #2
An alternative to the strategy #2 described above involves typing and copying the full formula from the Excel interface. In this case, you just need to follow these 2 simple steps:
Step #1: Type The Full Worksheet Formula You Want To Work With
In the case of the sample Find_Minimum macro, the worksheet formula that achieves the same result as the Min function is “=MIN(C5:C16)”.
The reason for this is that, in the macro, Min’s only argument is the variable my_Range which was previously defined as the range of cells from C5 to C16 of the worksheet named “Excel VBA Worksheet Function”.
Step #2: Repeat Steps #3 And #4 Of Strategy #2
Repeat the steps #3 and #4 that I explain above. In other words:
- Step #1: Copy the formula.
- Step #2: Paste the formula as a comment within the Visual Basic Editor.
The image below shows how this looks like in the case of the Find_Minimum sample macro. Notice how this syntax is substantially the same as that used when calling the Excel worksheet function in VBA.
Therefore, once more, you have very clear guidance in connection with the appropriate arguments and syntax to call the worksheet function.
Strategy #3: Use Auto List Members To Obtain A List Of Excel Worksheet Functions And Auto Quick Info To Get The Syntax Of A Function
When the Auto List Members option of the Visual Basic Editor is enabled, the VBE help you complete your VBA statements by displaying a list of items you can use. When the Auto Quick Info option is enabled, the Visual Basic Editor displays information about the arguments of (among others) Excel worksheet functions as you type them.
I provide a thorough explanation of how you can enable (in case they’re not enabled) Auto List Members and Auto Quick Info in The Beginner’s Guide To Excel’s Visual Basic Editor.
To see how the Auto List Members option works in practice, let’s go back to the VBA code of the sample Find_Minimum macro. Assume you’re typing the statement where the Min worksheet function is used (“minimum_Answer = Application.WorksheetFunction.Min (my_Range)”) and you’re standing just before the dot that separates the WorksheetFunction object from the Min method:
Once you type that dot, the Visual Basic Editor displays a list of items that may complete the statement. This includes Excel worksheet functions.
For example, in the case of the Find_Minimum macro, notice how the list displayed by the VBE after I type the dot (.) includes the Min function. In fact, you’ll notice that it includes several other familiar Excel worksheet functions such as:
As I explain above, Auto List Members only works as shown above when you include the reference to the WorksheetFunction property. In other words, in the case above:
- The Visual Basic Editor displays the list of members when you use the syntax (i) “Application.WorksheetFunction.” (as shown in the previous image) or (ii) “WorksheetFunction.” but…
- The VBE doesn’t show the list of members that includes Excel worksheet functions if you simply type “Application.”. In such a case, the Visual Basic Editor also lists members automatically. But these are the members of the Application object and, therefore, worksheet functions don’t appear.
Auto Quick Info works in a similar way to Auto List Members and you’ve seen a screenshot of it in action above. One of the main differences between Auto Quick Info and Auto List Members is the way in which they’re activated. Auto Quick Info displays the expected syntax for a particular Excel worksheet function once you’ve typed the first parenthesis after the function name.
For example, in the case of the Min worksheet function within the Find_Minimum sample macro, Auto Quick Info looks as follows.
Strategy #4: Use The Object Browser To Browse Through The Methods Of The WorksheetFunction Object
You can use the Object Browser to see available:
When working with Excel worksheet functions within VBA, you can use the Object Browser to obtain all the members of the WorksheetFunction object. Follow these 3 simple steps:
Step #1: Open The Object Browser
From within the Visual Basic Editor, open the Object Browser by doing any of the following:
- Option #1: Pressing the “F2” keyboard shortcut.
- Option #2: Clicking on the Object Browser button in the Standard toolbar.
- Option #3: Using the Object Browser command within the View menu.
Step #2: Select The Excel Library
At the top-left corner of the Object Browser, you find the Project/Library drop-down list. This list displays the libraries that are available.
Click on it and select the Excel library.
Step #3: Select The WorksheetFunction Object
The Classes box displayed on the left side of the Object Browser lists all the Excel objects. When working with Excel worksheet functions, the object that you’re interested in is WorksheetFunction.
Therefore, search and select “WorksheetFunction” in the Classes box.
The box on the right side of the Object Browser displays all the members of WorksheetFunction. These are, for the most part, all the Excel worksheet functions you can call with VBA by using the WorksheetFunction object.
For example, the Min function is one of the members that the Object Browser lists. Notice how, once I select “Min”, the Object Browser displays the syntax of the function (and its arguments) just below the list of members.
Strategy #5: Use Microsoft’s Online Help System To Get Information About A Particular Excel Worksheet Function
Microsoft’s Official Documentation includes a very thorough description of all the Excel worksheet functions that you can use in VBA.
If you’re working in the Visual Basic Editor and want to go directly to the relevant webpage for a particular worksheet function, follow the 3 easy steps below:
Step #1: Enter The Name Of An Excel Worksheet Function
For example, in the case of the sample Find_Minimum macro, the relevant Excel worksheet function is Min. Immediately after this function and its arguments are entered, the VBA code looks as follows:
Step #2: Place The Cursor On The Name Of The Function
In the case of the Find_Minimum macro and the Min function that I use as an example, this looks as follows:
Step #3: Press The F1 Key
F1 is the keyboard shortcut to access the help system. Once you press it, you’re generally taken to the relevant webpage within Microsoft’s Official Documentation.
For example, in the case above, I’m correctly taken to the page that covers the WorksheetFunction.Min method.
Among other useful information you can use while working with Excel worksheet functions within VBA, Microsoft’s Official Documentation usually explains:
- The syntax of the relevant worksheet function.
- The parameters of the function.
- The return value.
- Additional remarks that may be of interest or come in handy.
Notice how these 4 elements are all present in the page that corresponds to the Min worksheet function:
What Happens When An Excel Worksheet Function Can’t Be Used In VBA
Most Excel worksheet functions are available for use with Visual Basic for Applications.
However, there are a few cases where you can’t use an Excel worksheet function in VBA because it isn’t a method of the WorksheetFunction object. In those cases you’ll generally find an equivalent within Visual Basic for Applications.
In other words: Whenever there’s a particular VBA element (such as a built-in function or operator) that achieves a particular purpose, you can’t use the equivalent Excel worksheet function.
The following are some examples of such a situation:
- The MOD worksheet function. In such a case, you can rely on the (equivalent) Mod operator.
- The MONTH worksheet function. When using VBA, you can use the Month function.
- The SQRT function, whose functions are carried out within Visual Basic for Applications by the Sqr function.
- The TAN worksheet function. In place of TAN, you can use the Tan function.
- The LOWER and UPPER worksheet functions. When using VBA, you can obtain the equivalent results by using the LCase and UCase VBA functions.
As a consequence of this, consider proceeding as follows whenever you need to use a function within VBA:
- Step #1: Determine whether what you need exists within the Visual Basic for Applications framework.
- Step #2: If you’re not able to find something suitable within VBA, check out whether an Excel worksheet function could be of help. For these purposes, you can use the Insert Function dialog box to identify potentially useful functions, as I explain above.
- Step #3: If neither of the above steps works, you may be able to create a Function procedure to carry out the calculations you need.
You can use some of the strategies that I describe above for purposes of determining whether Visual Basic for Applications has a particular built-in function that you can use. Let’s check them out in the sections below.
Note, however, that sometimes the equivalent of an Excel worksheet function isn’t necessarily a VBA built-in function. One such a case is the MOD worksheet function which, as explained above, is replaced within VBA by the Mod operator. In such cases, you’ll need to adjust the strategies described below accordingly.
Strategy #1: Use Auto List Members To Obtain a List Of Built-In VBA Functions
This process is similar to that explained above for purposes of finding available Excel worksheet functions.
Note, however, that built-in VBA functions are not accessed through the WorksheetFunction object. This makes sense since, after all, they’re not worksheet functions.
The general syntax for referring to a VBA built-in function is as follows:
Where “Function_Name” is the relevant name of the built-in function. Usually, you’d omit the reference to VBA and simply type the Function_Name. But not when you want to use Auto List Members as described here:
In order to take advantage of Auto List Members when working with VBA built-in functions, you type VBA and a dot (.). After you’ve typed the dot, Excel displays the relevant list.
The image below shows how this looks like:
Strategy #2: Use The Object Browser To Browse Members Of The VBA Library
Once again, this strategy is substantially similar to the one I explain above for browsing through the methods of the WorksheetFunction Object.
Note, however, that built-in VBA functions are within the VBA (not the Excel) library. Therefore, instead of selecting the Excel library in the Project/Library list box, select “VBA”.
Once the VBA library is selected, Excel displays all of its classes and members. This includes the VBA built-in functions, which appear on the right side of the screen.
Strategy #3: Use Microsoft’s Official Documentation To Find VBA Built-In Functions
As you learned in a previous Section (strategy #5 to enter an Excel worksheet function in VBA), you can use the “F1” keyboard shortcut to access Microsoft’s Official Documentation.
Microsoft’s Official Documentation (also) contains a complete list of VBA built-in functions.
Conclusion
Excel worksheet functions are a great way to increase the power and flexibility of your macros.
After reading this Excel tutorial, you have all the basic tools you need to start using Excel worksheet functions in your macros. In particular, you now know:
- What an Excel worksheet function is.
- How you can call worksheet functions in VBA, including several strategies that can help you get some guidance when working with these functions.
- Which are the cases in which you can’t use Excel worksheet functions in VBA, how you can identify those cases and what to do in order to achieve your purposes.
This Excel VBA Worksheet Functions Tutorial is accompanied by an Excel workbook containing the data and macros I use above. You can get immediate free access to this example workbook by subscribing to the Power Spreadsheets Newsletter.
If you had a decent knowledge of Excel worksheet functions before reading this blog post, you have a great head start into this topic. As you’ve seen above, there are important similarities between using worksheet functions in VBA and using worksheet functions in Excel itself.
But even if you’re not that familiar with worksheet functions, don’t worry! Remember that you can always use the strategies listed above to find a function that is suitable for your purposes and understand its syntax.
So, if you haven’t yet, start using Excel worksheet functions in your VBA code to improve the power and flexibility of your macros.
Источник
Excel VBA: Calling Sub Procedures & Functions, Placement in Modules
———————————————————————————
Contents:
Sub procedures, Function Procedures & Property Procedures
Naming Rules & Conventions for Procedures
VBA Procedures Scope — Public vs Private
Placement of Macros / Sub procedures in appropriate Modules
Calling Procedures
Executing Procedures
———————————————————————————
Sub procedures, Function Procedures & Property Procedures
A VBA project can contain multiple modules, class modules and user forms. Each module contains one or more procedures viz. sub-procedures or functions. Procedures break a program into smaller and specific components. A VBA procedure, also referred to as a Macro, is defined as a set of codes which make Excel perform an action. A procedure is usually of two types, a sub procedure or a function. The third type of procedure is Property, used for Class Modules. As explained below in detail: sub-procedures do not return a value; functions return a value; property procedures are used to return and assign values, and set a reference to an object.
Sub procedures
Event Procedures — are predefined by VBA:
One category of sub procedures are Event Procedures which are triggered by a predefined event and are installed within Excel having a standard & predetermined name viz. like the Worksheet change procedure is installed with the worksheet — «Private Sub Worksheet_Change(ByVal Target As Range)», which combines the object name, underscore, and the event name. The other category of sub-procedures are those which are created by the user. For a detailed understanding of Event Procedures, refer our section: Excel VBA Events, Event Procedures (Handlers), Triggering a VBA Macro.
User Created Sub procedures:
Creating a sub procedure: A sub procedure declaration statement starts with the keyword Sub, followed by a name and then followed by a set of parentheses. A sub-procedure ends with an End Sub statement which can be typed but it also appears automatically on going to the next line after the Sub declaration statement is typed. Your vba code or statements are entered inbetween. See below example of a procedure named Greetings, running or executing which will return the message Welcome:
Sub Greetings()
MsgBox «Welcome!»
End Sub
Function Procedures
A sub-procedure is a set of vba codes or statements which perform an action, but does not «return a value». A Function is also used to perform an action or calculation (which can also be performed by a sub procedure) but «returns a value», which is a single value. The name of the function can be used within the function procedure to indicate the value returned by the function — refer Example 4 which shows the variance between how a function and sub works. Like you use built-in Excel functions of SUM, MAX, MIN, COUNT, AVERAGE, etc., Function procedures are created in vba to make custom worksheet functions. Function procedure cannot be created using a Macro Recorder. A sub procedure uses a different syntax as compared to a Function. A Function procedure can be called by using its name within an expression which is not possible in respect of a sub procedure which can be called only by a stand-alone statement. Because a function returns a value, it can be used directly in a worksheet (which is not possible with a sub-procedure), by entering/selecting the name of the function after typing an equal sign (refer Image 1).
Creating a Function procedure: A function declaration statement starts with the keyword Function, followed by a name and then followed by a set of parentheses. You must specify the data type which is the type of value the function will return — this is done by typing the keyword As (after the parentheses) followed by the data type. Functions can be created without arguments or with any number of arguments which are listed between the parentheses and in case of multiple arguments, separate them with commas. A function procedure ends with an End Function statement which can be typed but it also appears automatically on going to the next line after the Function declaration statement is typed. Your vba code or statements are entered inbetween the Function declaration statement & the End statement.
Executing a Function procedure: (i) the function can be called from another procedure viz. a sub-procedure or function procedure; and (ii) the function can be used directly in the spreadsheet viz. in a worksheet formula by entering/selecting the name of the function after typing an equal sign. See below examples of Function procedures and how they are called:
Example 1
Function partNames() As String
‘The declaration of the partNames function contains no argument.
Dim strFirstName As String
Dim strSurName As String
strFirstName = InputBox(«Enter first name»)
strSurName = InputBox(«Enter sur name»)
partNames = strFirstName & » » & strSurName
End Function
Sub fullName()
‘call the partNames function and place value in cell A1 of active sheet:
ActiveSheet.Range(«A1») = partNames
End Sub
Example 2
Function cubeRoot() As Double
‘The declaration of the cubeRoot function contains no argument.
Dim i As Integer
i = InputBox(«Enter an Integer»)
cubeRoot = i ^ (1 / 3)
cubeRoot = Format(cubeRoot, «#.##»)
End Function
Sub callCubeRoot()
‘call the cubeRoot function in the message box:
MsgBox «Cube Root of the number is » & cubeRoot
End Sub
Example 3 (refer section on Passing Arguments to Procedures, Excel VBA to understand how arguments are passed in a procedure)
Function triple(i As Integer) As Long
‘The declaration of the triple function contains one variable as argument.
triple = i * 3
End Function
Sub integerTriple()
Dim a As Integer
a = InputBox(«Enter an Integer»)
‘call the triple function:
MsgBox triple(a)
End Sub
Refer Image 1 which displays how the function is used in a worksheet.
It may be noted that the set of parentheses, after the procedure name in the Sub or Function declaration statement, is usually empty. This is the case when the sub procedure or Function does not receive arguments. However, when arguments are passed to a sub procedure or a Function from other procedures, then these are listed between the parentheses.
Refer section on Passing Arguments to Procedures, Excel VBA to understand how arguments are passed in a procedure.
Example 4: shows the variance between how a function and sub works — functions return a value whereas sub-procedures do not return a value.
For live code, click to download excel file.
The addSquare function returns a value which can be used by the calling procedure:
Function addSquare() As Double
‘the addSquare function returns a value in its own name:
Dim a As Double
Dim b As Double
a = InputBox(«Enter first number»)
b = InputBox(«Enter second number»)
addSquare = (a + b) ^ 2
End Function
Sub calculate()
‘This is the calling procedure: calls the addSquare function.
Dim c As Double
‘the addSquare function returns a value which can be used by the calling procedure:
c = addSquare ^ (1 / 2)
MsgBox c
End Sub
The addSquare1 sub-procedure does NOT return a value which can be used by the calling procedure:
Sub addSquare1()
Dim a As Double
Dim b As Double
Dim c As Double
a = InputBox(«Enter first number»)
b = InputBox(«Enter second number»)
c = (a + b) ^ 2
MsgBox c
End Sub
Sub calculate1()
‘This is the calling procedure: calls the addSquare1 sub procedure.
‘the addSquare1 sub-procedure does NOT return a value which can be used by the calling procedure. The calling procedure (calculate1) can only call the addSquare1 sub-procedure without being able to use its result:
addSquare1
End Sub
Property Procedures
For a detailed understanding of Property Procedures, refer section Custom Classes & Objects, Custom Events, using Class Modules in Excel VBA.
Property Procedure is a set of vba codes that creates and manipulates custom properties for a class module. The properties of the class object are manipulated in a Class Module with Property procedures which use the Property Let, Property Get, and Property Set statements. A Property procedure is declared by a Property Let, Property Get or Property Set statement and ends with an End Property statement. Property Let (write-only property) is used to assign a value to a property and Property Get (read-only property — which can only be returned but not set) returns or retrieves the value of a property. Property Set (write-only property) is used to set a reference to an object. Property procedures are usually defined in pairs, Property Let and Property Get OR Property Set and Property Get. A Property Let procedure is created to allow the user to change or set the value of a property, whereas the user cannot set or change the value of a read-only property (viz. Property Get).
A property procedure can do whatever can be done within a vba procedure like performing an action or calculation on data. A Property Let (or Property Set) procedure is an independent procedure which can pass arguments, perform actions as per a set of codes and change the value of its arguments like a Property Get procedure or a Function but does not return a value like them. A Property Get procedure is also an independent procedure which can pass arguments, perform actions as per a set of codes and change the value of its arguments like a Property Let (or Property Set) procedure, and can be used similar to a Function to return the value of a property.
The Property Set procedure is similar to and a variation of the Property Let procedure and both are used to set values. A Property Set procedure is used to create object properties which are actually pointers to other objects, whereas a Property Let procedure sets or assigns values to scalar properties like string, integer, date, etc. Using the Property Set statement enables Properties to be represented as objects.
Naming Rules & Conventions for Procedures
It will help to assign a procedure name which is reflective of the action you wish to perform with the procedure. Some programmers prefer to use a sentence, differentiating words by an underscore or a capital letter viz. total_number_of_rows, TotalNumberOfRows. Use of very lengthy names names is generally avoidable.
There are some rules which are to be followed when naming your procedures:
The name must begin with a letter, and not a number or underscore.
A name can consist of letters, numbers or underscores but cannot have a period (.) or punctuation characters or special characters (such as ! @ # $ % ^ & * ( ) + — = [ ] { } ; ‘ : » , . / < > ? | ` ~).
The name should consist of a string of continuous characters, with no intervening space.
A procedure name can have a maximum of 255 characters.
Procedure names cannot use keywords / reserved words such as If, And, Or, Loop, Do, Len, Close, Date, ElseIf, Else, Select, … that VBA uses as part of its programming language.
Valid Names:
TotalRows
total_rows_10
Total_number_of_Rows
Invalid Names:
Total.Rows
5Rows
Total&Rows
Total Rows (space not allowed)
VBA Procedures Scope — Public vs Private
A vba procedure can have either Public or Private Scope. A procedure can be specified as such by preceding it with the Public or Private keyword. Procedures are Public by default, if the Public keyword is not specified.
A Private procedure can only be called by all procedures in the same module and will not be visible or accessible to procedures of outside modules in the project. A Private procedure will also not appear in the Macros dialog box. A
Public procedure can be called by all procedures in the same module and also by all procedures of outside modules in the project. A Public procedure’s name will appear in the Macros dialog box and can be run therefrom.
Creating a Public procedure:
Sub calculateProcedure()
Public Sub calculateProcedure()
Function cubeRoot() As Double
Public Function cubeRoot() As Double
Creating a Private procedure:
Private Sub calculate()
Private Function cubeRoot() As Double
Placement of Macros / Sub procedures in appropriate Modules
Macros (viz. vba codes or sub-procedures) should reside in their appropriate modules or Excel will not be able to find and execute them. The Object Modules are used for Excel built-in event procedures and to create your own events. Object Modules in Excel are: ThisWorkbook module, Sheet modules (worksheets and chart sheets), UserForm modules and Class modules. General vba code in respect of events not associated with a particular object (like workbook or worksheet) are placed in the standard code module. A generally accepted practice is to place event procedures in the ThisWorkbook module, Sheet modules and UserForm modules, while placing other vba codes in Standard Code modules.
Refer Image 2 which shows the Modules in VBE.
Standard Code Modules:
These are also referred to as Code Modules or Modules, and there can be any number of these Modules (Module1, Module2, …) in a VBA project, wherein each Module can be used for covering a certain aspect of the project. Most vba codes and custom functions (viz. User Defined Functions referred to as UDFs) are placed in Standard Code Modules. Standard Code Modules are not used for event procedures linked and associated to a Workbook or Worksheet or UserForm or for Application events created in a Dedicated Class Module. In respect of events not associated with objects, such as OnTime method (automatically trigger a vba code at periodic intervals or at a specific day or time) and OnKey method (run a specific code on pressing a key or combination of keys), because these are not associated with a particular object like workbook or worksheet, their codes rest in the standard code module. Procedures in standard modules can be called from a procedure in an outside module just like you call a procedure located in the same module ie. without specifying the module of the called procedure.
Workbook module:
ThisWorkbook is the name of the module for the workbook and is used to place workbook events and Application Events. Workbook events are actions associated with the workbook, to trigger a VBA code or macro. Opening / closing / saving / activating / deactivating the workbook are examples of workbook events viz. with a workbook open event, you can run a sub-procedure automatically when a workbook is opened. Workbook events code must be placed in the code module for the ThisWorkbook object, and if they are placed in standard code modules, Excel will not be able to find and execute them. Though Application Events can be created in any object module, they are best placed in either an existing object module like ThisWorkbook or you can create a class module to handle them. Though general vba codes and procedures can also be placed in a workbook, but you will need to include ‘ThisWorkbook’ in the reference to call them (from outside the workbook module) viz. ThisWorkbook.ProcedureName.
Sheet Modules:
A sheet module has the same name as the worksheet’s code name with which it is associated viz. Sheet1, Sheet2, … In VBE, the code name of the selected worksheet appears to the right of (Name) in the Properties Window while the sheet name appears to the right of Name when you scroll down in the Properties Window. The code name can be changed only in the Properties window and not programmatically with code. Sheet module can be for a worksheet or a chart sheet and is used to place worksheet and chart sheet events. Worksheet events are actions or occurrences associated with the worksheet, to trigger a VBA code or macro. Chart sheet events (ie. if a chart is a chart sheet) reside within its chart sheet and are enabled by default, similar to as worksheet events reside in their worksheet. But for using events for a chart object representing an embedded chart in a worksheet, a new class module has to be created.
To use the Excel provided worksheet event procedures, in the Visual Basic Editor after selecting the appropriate worksheet, select Worksheet from the Object box and then select a corresponding procedure from the Procedure box. After selecting the specific event, insert the vba code you want to be executed. Worksheet Event procedures are installed with the worksheet, ie. the code must be placed in the code module of the appropriate Sheet object and if they are placed in standard code modules, Excel will not be able to find and execute them. Instances of worksheet events are: selecting a cell or changing cell selection in a worksheet, making a change in the content of a worksheet cell, selecting or activating a worksheet, when a worksheet is calculated, and so on. For example, with the worskheet change event, a sub-procedure runs automatically when you change the contents of a worksheet cell. Though general vba codes and procedures can also be placed in a worksheet, but you will need to include the sheet module name in the reference to call them (from outside that sheet module) viz. Sheet3.ProcedureName.
UserForm Modules:
Event procedures for UserForm or its Controls are placed in the Code module of the appropriate UserForm. UserForm events are pre-determined events that occur for a particular UserForm and its Controls, examples include Initialize, Activate or Click. These are placed in the user form code module. You must double-click the body of a UserForm to view the UserForm Code module, referred to as a module ‘behind’ the UserForm, and then select UserForm or its Control from the Object box and then select a corresponding procedure from the Procedure box. After selecting the specific event, insert the vba code you want to be executed. Remember to set the Name property of controls before you start using event procedures for them, else you will need to change the procedure name corresponding to the control name given later. Only event procedures for the UserForm or its controls should be placed here. However, general vba codes and procedures can also be placed in a UserForm, but you will need to include the UserForm module name in the reference to call them (from outside that UserForm module) viz. UserForm1.ProcedureName.
Class Modules:
Class Modules are used to create new objects and you can create your own custom events in a class. A Custom Event is defined and declared in a Class Module using the Event keyword. An Event procedure can be created using the WithEvents keyword to declare an object variable of the Class Module type. Though Application Events can be created in any object module, they are best placed in either an existing object module like ThisWorkbook or by creating a class module to handle them. Also, for using events for a chart object representing an embedded chart in a worksheet, a new class module has to be created.
For a detailed understanding of Class Modules, refer section Custom Classes & Objects, Custom Events, using Class Modules in Excel VBA.
Calling Procedures
Subs and Functions can be called within each other. Calling a procedure refers to using or executing a procedure.
Calling Sub procedures in the Same Module
You can call sub-procedures either solely by their name or precede the name with the Call keyword.
Calling a sub named strGetName which does not receive arguments, which was declared as — Sub strGetName():
strGetName
Call strGetName
Calling a sub named strGetName which receives arguments, which was declared as — Sub strGetName(firstName As String, secondName As String):
Call strGetName(firstName, secondName)
strGetName firstName, secondName
Note that argument(s) must be enclosed within parentheses when using the Call keyword, and multiple arguments must omit the parentheses when the Call keyword is not used.
Calling Functions in the Same Module
Functions can be called in a manner similar to Subs and can also be used in an expression by their name. Functions can also be used directly in a worksheet, by entering/selecting the name of the function after typing an equal sign (refer Image 1 for using the Example 3 function in a worksheet).
A function declared as — Function studentNames() As String — can be called as below:
studentNames
Call studentNames
A function which receives arguments and declared as — Function triple(i As Integer, j As Integer) As Long — can be called as below:
Call triple(i, j)
triple i, j
Using a Function in an expression: A function declared as — Function cubeRoot() As Double — can be called as below:
MsgBox cubeRoot * 2
Calling Procedures in Outside Modules
As explained above, Public procedures can be called by all procedures of outside modules. To do so, it is mostly required to specify the module that contains the called procedure. There are different ways to call procedures located in a workbook/ worksheet/ form module, standard module or a class module.
Calling Procedures located in a Workbook Module, Worksheet Module or Forms Module
If the called procedure is located in a Workbook Module, Worksheet Module or Forms Module, then you will need to specify the module while calling it from an outside module.
A sub named strGetName, which was declared as — Sub strGetName() — and located in the workbook module named ThisWorkbook, can be called by specifying — ThisWorkbook.strGetName — in the calling procedure located in an outside module.
A sub named strGetName, which was declared as — Sub strGetName() — and located in the worksheet module named Sheet2, can be called by specifying — Sheet2.strGetName — in the calling procedure located in an outside module.
A sub named strGetName, which was declared as — Sub strGetName() — and located in the UserForm named UserForm1, can be called by specifying — UserForm1.strGetName — in the calling procedure located in an outside module.
Calling Procedures located in Standard Modules
Procedures in standard modules can be called from a procedure in an outside module just like you call a procedure located in the same module ie. without specifying the module of the called procedure. A sub named strGetName, which was declared as — Sub strGetName() — and located in a standard module, can be called from a procedure in a worksheet module by using only its name ie. strGetName, or using the Call keyword ie. Call strGetName.
You might already be aware that procedures of same name are not allowed within the same module but procedures can have same names in separate modules. If both the standard modules (Module1 and Module2) have a procedure named strGetName, to call it from an outside module (say, from a standard module named Module3), you will need to specify the called procedure’s module viz. Module1.strGetName OR Module2.strGetName. However, if the calling procedure is located in Module2 and if you call the procedure named strGetName without specifying the module, then the procedure strGetName located in Module 2 will be called.
Calling Procedures located in Class Modules
In the calling procedure located in an outside module, you need to instantiate an instance of the class in which the called procedure is located. To do this, you create a variable and definine it as a reference to the class. Use this variable with the name of the called procedure located in the class module. For example, in the calling procedure use the statement — Dim iStudent As New clsStudent — to use a variable named iStudent and create an instance of the class named clsStudent. To call the Grade function located in the clsStudent object, use the variable with the function name — iStudent.Grade. If the Grade function receives an argument, then to call the Grade function — iStudent.Grade (argument).
For a detailed understanding of Class Modules, refer section Custom Classes & Objects, Custom Events, using Class Modules in Excel VBA.
Executing Procedures
Executing Function Procedures:
Executing a Function procedure: (i) the function can be called from another procedure viz. a sub procedure or function procedure; and (ii) the function can be used directly in the spreadsheet viz. in a worksheet formula by entering/selecting the name of the function after typing an equal sign. To see examples of Function procedures and how they are called, refer the headings «Function Procedures» & «Calling Procedures» hereinabove.
Executing Event Procedures:
Events are actions performed, or occurrences, which trigger a VBA macro. An event procedure (ie. a vba code) is triggered when an event occurs such as opening / closing / saving / activating / deactivating the workbook, selecting a cell or changing cell selection in a worksheet, making a change in the content of a worksheet cell, selecting or activating a worksheet, when a worksheet is calculated, and so on.
Event procedures are attached to objects: An event procedure is a procedure with a standard name that runs on the occurrence of a corresponding event. The event procedure contains the user written customized code which gets executed when the specific Excel built-in event, such as worksheet change event, is triggered. Event Procedures are triggered by a predefined event and are installed within Excel having a standard & predetermined name viz. like the Worksheet change procedure is installed with the worksheet — «Private Sub Worksheet_Change(ByVal Target As Range)». An Event Procedure is automatically invoked when an object recognizes the occurrence of an event. Event procedures are attached to objects like Workbook, Worksheet, Charts, Application, UserForms or Controls. An event procedure for an object is a combination of the object’s name (as specified in the Name property), an underscore and the event name. To use the Excel provided event procedures, in the Visual Basic Editor select an object from the Object box and then select a corresponding procedure from the Procedure box. After selecting the specific event, insert the vba code you want to be executed.
Using ActiveX controls: ActiveX controls are used: 1) on worksheets — these can be used without or with vba code here; and 2) on UserForms, with vba code. ActiveX controls have event procedures that run on the occurrence of a corresponding event. These procedures are inserted in the code modules of the Worksheet or UserForm within which the controls are used. Some ActiveX controls can only be used on UserForms and not on worksheets. Note that you can assign macros to run directly from Forms controls, but you cannot assign a macro to run directly from ActiveX controls.
Using an ActiveX Control viz. Command Button, in a worksheet: On the Developer tab on the ribbon, click Insert in the Controls group, choose and click Command Button in ActiveX Controls and then click on your worksheet where you want to place the upper-left corner of the Command Button (you can move and resize later). To create an event procedure with the command button, in the code window in VBE, select the command button in the Object drop-down Box on the left, select the relevant event from the Procedure drop-down Box on the right, and insert the vba code. For example, if Click is selected in the Procedure drop-down Box after selecting CommandButton1 in the Object drop-down Box, the event procedure will be called CommandButton1_Click, and the vba code runs on clicking the Command Button.
Events not associated with objects, such as OnTime method (automatically trigger a vba code at periodic intervals or at a specific day or time) and OnKey method (run a specific code on pressing a key or combination of keys). Because these are not associated with a particular object like workbook or worksheet, their codes rest in the standard code module.
Executing Sub Procedures:
Run a Sub procedure (macro) using Macro dialog box, Shortcut key or in VBE:
Macro dialog box: Under the View tab on the ribbon, click Macros in the Macros group, click View Macros which will open the Macro dialog box. In the Macro dialog box, select the Macro name and click Run to execute the Sub/macro. You can also open the Macro dialog box by clicking on Macros in the Code group under the Developer tab on the ribbon. Yet another way is to use the key combination Alt+F8 which opens the Macro dialog box.
Shortcut key: Use the Shortcut key associated with the macro. For this you must already have assigned a Shortcut key to the macro which can be done both at the time when you begin recording a macro or later by selecting the sub / macro name in the macro list (in Macro dialog box) and clicking Options button.
Visual Basic Editor: 1) In the Visual Basic Editor, click within the sub procedure and press F5 (or click Run in the menu bar and then click Run Sub/Userform). 2) In the Visual Basic Editor, click Tools in the menu bar, then click Macros which opens the Macros dialog box. In the Macros dialog box, select the Macro name and click Run to execute the macro,
Obviously these methods are not very user friendly and you will not wish to automate an excel file with multiple macros and have users go through a «process» as described above, to select and run macros. A better way to run a macro would be to click on a button bearing a self-explanatory text «Calculate Bonus» appearing on the worksheet or clicking a Toolbar Button. We show how to assign a macro to an object, shape, graphic or control.
You can assign a sub / macro to:
A Form Control viz. Button: You can assign a macro to any Form control. On the Developer tab on the ribbon, click Insert in the Controls group, choose and click Button in Form Controls and then click on your worksheet where you want to place the the upper-left corner of the Button (you can move and resize later). Right click on the Button and select Assign Macro which opens the Assign Macro dialog box from where you can select and assign a macro to the Button.
The Quick Access Toolbar (Toolbar Button): Click the Office Button (top left of your excel window), click Excel Options which opens the Excel Options dialog box. Click Customize on the left, In the ‘Choose commands from’ drop-down box, select Macros, select a macro name on the left side list box and click ‘Add’ which adds it to the Quick Access Toolbar and the macro name now appears on the right side list box. To modify the macro button: select the macro name on the right side list box, click the Modify button at the bottom which opens the Modify Button dialog box from which you can select and modify the button which appears on the Quick Access Toolbar. Clicking this button on the Quick Access Toolbar will run the macro. Refer Image 3a which shows the Excel Options dialog box after selecting a macro; Image 3b shows (after clicking Add and Modify) the Modify Button dialog box wherein a new button is assigned for the macro; Image 3c (after clicking Ok twice) shows the macro button (i in blue circle) appearing on the Toolbar (we have assigned macro called macro1 in Sheet1 — Sheet1.macro1).
Any Object, Shape, Picture, Chart, Text Box, etc. inserted in the worksheet: Under the Insert tab on the ribbon, you can insert an Object, Shape, Picture, SmartArt graphic, Chart, Text Box, WordArt, etc. in the worksheet. Right click on the object, shape or graphic you have inserted, and select Assign Macro which opens the Assign Macro dialog box from where you can select and assign a macro to the Button.
Calling a Sub procedure from another Procedure:
Subs and Functions can be called within each other, as explained above under the heading «Calling Procedures». This means that a sub-procedure (or function) can be called from another procedure viz. a sub procedure or function procedure.
Assign multiple subs / macros:
You can assign multiple subs/macros to an object, graphic or control, by calling other sub procedures. Refer below example, in the sub procedure (CommandButton1_Click) which is executed on clicking a Command Button, two other sub procedures named macro1 and macro2 are called and executed. In this example macros are called using their names. You can view all macros by clicking Macros in the Macros group (under the View tab on the ribbon) and then selecting View Macros. Remember to type the macro names on separate lines while calling them.
Call sub procedures (macro1 & macro2 are located in standard code modules) using their names:
Private Sub CommandButton1_Click()
macro1
macro2
End Sub
Call sub procedures (using the Call method) where macro1 & macro2 are located in standard code modules and macro3 is in a worskheet module (in Sheet3) and macro4 is in the workbook module (ThisWorkbook), as shown below:
Private Sub CommandButton1_Click()
Call macro1
Call macro2
Call Sheet3.macro3
Call ThisWorkbook.macro4
End Sub