Call excel functions in vba

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.

vba function no argument

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.

vba function no argument 1

The value of 50 would always be returned.

You can also call the GetRange function from a Sub Procedure.

vba function no argument range

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.

vba function return value

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.

vba functions return values 1

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.

vba-function-2-arguments

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 function optional parameter

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!

automacro

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

vba functions optional default

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

vba function by ref

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.

vba function byval

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 function exit function

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.

vba function fx

Select User Defined from the Category List

vba function udf

Select the function you require from the available User Defined Functions (UDF’s).

vba function excel sheet

Alternatively, when you start writing your function in Excel, the function should appear in the drop down list of functions.

vba function dropdown

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.

vba function dropdown 2

Interestingly enough, however, you can still use the function – it just will not appear in the list when looking for it!

vba function excel

If you have declared the second argument as Optional, you can omit it within the Excel sheet as well as within the VBA code.

vba function excel 2

You can also use the a function that you have created without arguments in your Excel sheet.

vba function no argument excel

Excel VBA Tutorial about Worksheet FunctionsIf 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:

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:

  1. Excel worksheet functions. This is the main topic of this Excel tutorial.
  2. VBA built-in functions. I write about this topic briefly below, but it’s not the main focus of this tutorial.
  3. 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:

  1. The user (you) feeds data to the function.
  2. The function:
    • Carries out calculations.
    • Returns values.
  3. The user (you) can use the function’s output in the VBA code.

In other words, functions (generally):

  • Carry out a calculation; and
  • Return a value.

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.

Worksheet functions in Excel 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.

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:

Sample table to use worksheet function in VBA

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.

Example macro with Min worksheet function

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:

Example result of MIN worksheet function in VBA

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:

Application.WorksheetFunction.Min(my_Range)

The following screenshot shows its location within the VBA code:

VBA code example using worksheet function

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:

WorksheetFunction.Min(my_Range)

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

You can:

  • 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:

Application.Min(my_Range)

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.

You:

  • 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.
    Insert worksheet function in Excel
  • 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.

Description of worksheet function for use in VBA

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.

Open Function arguments dialog

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:

Worksheet function argument description

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.

Worksheet function argument description in VBA

Notice how:

  • 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.

Excel worksheet formula with MIN function

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:

Insert arguments of Excel worksheet function for VBA

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.

Excel worksheet formula selected

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.

Step #4: Paste The Worksheet Formula As A Comment In The Visual Basic Editor

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.

Excel worksheet function syntax guidance in VBA

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)”.

Excel worksheet formula for function argument guidance

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”.

Worksheet function argument definition in VBA

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.

Macro with comment explaining function syntax

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:

VBE between WorksheetFunction object and 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:

  • Match;
  • Max; and
  • Median.

Excel worksheet function suggestions for use in VBA

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.

Worksheet function argument syntax within VBA

Strategy #4: Use The Object Browser To Browse Through The Methods Of The WorksheetFunction Object

You can use the Object Browser to see available:

  • Objects.
  • Methods.
  • Properties.

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:

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.

Get to Excel library in VBA for worksheet functions

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.

WorksheetFunction object in VBE Object Browser

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.

Min worksheet function for VBA within Object Browser

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:

Example of macro after entering worksheet function name

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:

Cursor over name of worksheet function in VBE

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.

Help system for WorksheetFunction.Min function

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:

VBA worksheet function description in MSDN

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:

VBA.Function_Name

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:

Example of VBA built-in functions

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”.

Access VBA built-in functions in Object Browser

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.

VBA Built-In Functions

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.

ThreeWave
Calling Worksheet Functions From VBA

This page describes how to call worksheet functions from VBA code.
ShortFadeBar

Because VBA is used by many applications beyond Excel, the Excel worksheet functions are not part of the VBA language itself.
However, you can call worksheet functions directly through the Application object or through the
Application.WorksheetFunctions class. The difference between using or omitting the
WorksheetFunctions reference is how errors are handled. This is discussed below.

SectionBreak

Nearly all worksheet functions can be called from VBA using the Application or Application.Worksheet
objects. Excel functions that have native VBA equivalents, such as Month, are not available. The syntax of a
worksheet function call is the same as worksheet function itself. For example, a worksheet function in a cell might be:

=VLOOKUP(123,A1:C100,3,FALSE)

To use code in VBA that does the same thing, you would use:

Dim Res As Variant
Res = Application.WorksheetFunction.VLookup(123,Range("A1:C100"),3,FALSE)

The number of parameters and their meanings are the same when calling the function from VBA as they are when calling the function
from a worksheet cell. As the code above is written, you will get a runtime error if the value 123 is not
found in the range. Therefore, you need to put in some error trapping code:

Dim Res As Variant
On Error Resume Next
Err.Clear
Res = Application.WorksheetFunction.VLookup(123,Range("A1:C100"),3,FALSE)
If Err.Number = 0 Then 
    
Else
    
End If 

SectionBreak

This brings us to the topic of error handling when calling worksheet functions in VBA. As noted earlier, there are two basic
syntaxes you can use. You can either use an On Error statement and then test the
Err.Number value to see if an error occurred, or you can declare the result variable as a
Variant type and use IsError to see if that variable is an Error
type variant. Which method you use depends on whether you use the WorksheetFunction property
in your code. If you do include the WorksheetFunction property, errors will manifest themselves as
runtime error that need an On Error statement and a test of the Err.Number
value. If you do not include the WorksheetFunction property, you must declare the result variable as
a Variant type and test that variable with the IsError function. Examples
of both are shown below.

Dim Res As Variant
On Error Resume Next
Err.Clear
Res = Application.WorksheetFunction.VLookup(123,Range("A1:C100"),2,False)
If Err.Number = 0 Then
    
Else
    
End If


Dim Res As Variant
Res = Application.VLookup(123,Range("A1:C100"),2,False)
If IsError(Res) = False Then
    
Else
    
End If

There is no significant difference between the two syntaxes of calling worksheet function. It is largely a matter
of personal preference whether to use the WorksheetFunction property. In general, I omit it and
use IsError to detect an error.

SectionBreak

Prior to Excel 2007, the functions provided by the Analysis Tool Pack (ATP) are provided by a separate add-in. You cannot call
them using the methods shown above. First, you must load the Analysis Tool Pack — VBA add-in. Note that this is different from the
Analysis Tool Pack item. Once this add-in is loaded, go to VBA, open your project, and choose References from the
Tools menu. In that dialog, choose atpvbaen.xls in the list of references. Once you have that reference in place
in your VBA code, you can call the functions in the ATP as if they were native VBA functions. For example,

Dim Res As Variant
Res = MRound(123.456, 0.5)
Debug.Print Res

If there is the possibility that you will have a procedure with the same name as an ATP function, you can prefix the function name
with the library name to ensure you are calling the correct function. For example,

Dim Res As Variant
Res = [atpvbaen.xls].MRound(123.456, 0.5)
Debug.Print Res

Note that the square brackets ([ ]) are required in the library name because the name contains a period. The name
of the add-in is an abbreviation of Analysis Tool
Pack VBA ENglish.
.
If you are using a language other than English, the last two characters of the
add-in name will be the language name abbreviation.

This page last updated: 20-October-2007

Skip to content

VBA code to call a function

Home » VBA » 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
Effortlessly Manage Your Projects and Resources
120+ Professional Project Management 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
Excel VBA Project Management Templates
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

  1. Rajadurai16
    March 16, 2017 at 4:18 PM — Reply

    Timer vba codes

    Dim binNew As Boolean
    Dim TRows, THows, i As Long

    Private 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 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

    CmdSave.Enabled = False
    CmdDelete.Enabled = False

    End 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)) Then

    txtEmpNo.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).Value

    Exit 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

With Our Professional and Premium Project Management Templates!

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.

Analysistabs Logo

Page load link

Go to Top

Содержание

  1. Using Excel worksheet functions in Visual Basic
  2. Calling a worksheet function from Visual Basic
  3. Inserting a worksheet function into a cell
  4. Example
  5. See also
  6. Support and feedback
  7. Использование функций листов Excel в Visual Basic
  8. Вызов функции листа из Visual Basic
  9. Вставка функции листа в ячейку
  10. Пример
  11. См. также
  12. Поддержка и обратная связь
  13. VBA Function – Call, Return Value, & Parameters
  14. Creating a Function without Arguments
  15. Calling a Function from a Sub Procedure
  16. Creating Functions
  17. Single Argument
  18. Multiple Arguments
  19. Optional Arguments
  20. VBA Coding Made Easy
  21. Default Argument Value
  22. ByVal and ByRef
  23. Exit Function
  24. Using a Function from within an Excel Sheet
  25. VBA Code Examples Add-in

Using Excel worksheet functions in Visual Basic

Use most Microsoft Excel worksheet functions in your Visual Basic statements. For a list of the worksheet functions you can use, see List of worksheet functions available to Visual Basic.

Some worksheet functions are not useful in Visual Basic. For example, the Concatenate function is not needed because in Visual Basic you can use the & operator to join multiple text values.

Calling a worksheet function from Visual Basic

In Visual Basic, the Excel worksheet functions are available through the WorksheetFunction object.

The following Sub procedure uses the Min worksheet function to determine the smallest value in a range of cells. First, the variable myRange is declared as a Range object, and then it is set to range A1:C10 on Sheet1. Another variable, answer , is assigned the result of applying the Min function to myRange . Finally, the value of answer is displayed in a message box.

If you use a worksheet function that requires a range reference as an argument, you must specify a Range object. For example, you can use the Match worksheet function to search a range of cells. In a worksheet cell, you would enter a formula such as =MATCH(9,A1:A10,0). However, in a Visual Basic procedure, you would specify a Range object to get the same result.

Visual Basic functions don’t use the WorksheetFunction qualifier. A function may have the same name as a Microsoft Excel function and yet work differently. For example, Application.WorksheetFunction.Log and Log will return different values.

Inserting a worksheet function into a cell

To insert a worksheet function into a cell, you specify the function as the value of the Formula property of the corresponding Range object. In the following example, the RAND worksheet function (which generates a random number) is assigned to the Formula property of range A1:B3 on Sheet1 in the active workbook.

Example

This example uses the worksheet function Pmt to calculate a home mortgage loan payment. Notice that this example uses the InputBox method instead of the InputBox function so that the method can perform type checking. The Static statements cause Visual Basic to retain the values of the three variables; these are displayed as default values the next time you run the program.

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 Function – Call, Return Value, & Parameters

In this Article

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.

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.

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.

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.

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 .

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!

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.

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.

In the function above, the ByRef could be omitted and the function would work the same way.

To call this function, we can run a sub-procedure.

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.

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.

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.

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.

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 Examples Add-in

Easily access all of the code examples found on our site.

Simply navigate to the menu, click, and the code will be inserted directly into your module. .xlam add-in.

Источник

I am a VBA newbie, and I am trying to write a function that I can call from Excel cells, that can open a workbook that’s closed, look up a cell value, and return it.

So far I know how to write a macro like this:

Sub OpenWorkbook()
    Dim path As String
    path = "C:UsersUserNameDesktopTestSample.xlsx"

    Dim currentWb As Workbook
    Set currentWb = ThisWorkbook


    currentWb.Sheets("Sheet1").Range("A1") = OpenWorkbookToPullData(path, "B2")
End Sub


Function OpenWorkbookToPullData(path, cell)

    Dim openWb As Workbook
    Set openWb = Workbooks.Open(path, , True)

    Dim openWs As Worksheet
    Set openWs = openWb.Sheets("Sheet1")

    OpenWorkbookToPullData = openWs.Range(cell)

    openWb.Close (False)

End Function

The macro OpenWorkbook() runs perfectly fine, but when I am trying to call OpenWorkbookToPullData(…) directly from an Excel cell, it doesn’t work. The statement:

    Set openWb = Workbooks.Open(path, , True)

returns Nothing.

Does anyone know how to turn it into a working VBA function that can be called from Excel cell?

Like this post? Please share to your friends:
  • Call dll from excel
  • Calendars templates for excel
  • Calendar month in word
  • Calendar export to excel
  • Calendar events in excel