Using functions in excel vba

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.

Excel VBA Functions

We have seen that we can use the worksheet functions in VBA, i.e., the Excel worksheet functions in VBA coding using the Application.Worksheet method. But how do we use a function of VBA in Excel well? Such functions are called user-defined functions. When a user creates a function in VBA, we can use it in an Excel worksheet.

Although we have many functions in Excel to manipulate the data, sometimes we need to have some customization in the tools to save time as we do some tasks repeatedly. For example, we have predefined functions in excel like SUM, COUNTIFThe COUNTIF function in Excel counts the number of cells within a range based on pre-defined criteria. It is used to count cells that include dates, numbers, or text. For example, COUNTIF(A1:A10,”Trump”) will count the number of cells within the range A1:A10 that contain the text “Trump”
read more
, SUMIFThe SUMIF Excel function calculates the sum of a range of cells based on given criteria. The criteria can include dates, numbers, and text. For example, the formula “=SUMIF(B1:B5, “<=12”)” adds the values in the cell range B1:B5, which are less than or equal to 12.
read more
, COUNTIFS,”COUNTIFSread more VLOOKUPThe VLOOKUP excel function searches for a particular value and returns a corresponding match based on a unique identifier. A unique identifier is uniquely associated with all the records of the database. For instance, employee ID, student roll number, customer contact number, seller email address, etc., are unique identifiers.
read more
, INDEX, MATCH in excelThe MATCH function looks for a specific value and returns its relative position in a given range of cells. The output is the first position found for the given value. Being a lookup and reference function, it works for both an exact and approximate match. For example, if the range A11:A15 consists of the numbers 2, 9, 8, 14, 32, the formula “MATCH(8,A11:A15,0)” returns 3. This is because the number 8 is at the third position.
read more
, etc., but we do some tasks daily for which a single command or function is not available in Excel. Using VBA, we can create the User Defined Functions (UDFUser Defined Function in VBA is a group of customized commands created to give out a certain result. It is a flexibility given to a user to design functions similar to those already provided in Excel.read more) custom function.

Table of contents
  • Excel VBA Functions
    • What do VBA Functions do?
    • How to Create Custom Functions using VBA?
      • Example
        • Step 1: Find Total Marks
        • Step 2: Create ResultOfStudent Function
        • Step 3: Apply ResultOfStudents Function to Get Result
        • Step 4: Create ‘GradeForStudent’ Function to get Grades
    • Recommended Articles

VBA Functions

You are free to use this image on your website, templates, etc, Please provide us with an attribution linkArticle Link to be Hyperlinked
For eg:
Source: VBA Functions (wallstreetmojo.com)

What do VBA Functions do?

  • They carry out certain calculations; and
  • Return a value

In VBA, while defining the function, we use the following syntax to specify the parameters and their data type.

Data type here is the type of dataData type is the core character of any variable, it represents what is the type of value we can store in the variable and what is the limit or the range of values which can be stored in the variable, data types are built-in VBA and user or developer needs to be aware which type of value can be stored in which data type. Data types assign to variables tells the compiler storage size of the variable.read more the variable will hold. It can hold any value (data type or class object).

Marks as Integer

We can connect the object with its property or method using the period or dot (.) symbol.

How to Create Custom Functions using VBA?

You can download this VBA Function Excel Template here – VBA Function Excel Template

Example

Suppose we have the following data from a school where we need to find the total marks scored by the student, result, and grade.

VBA Function Example 1

To sum up, the marks scored by an individual student in all subjects, we have an inbuilt function, SUM. But, determining the grade and result based on the criteria set out by the school is not available in Excel by default.

It is the reason why we need to create user-defined functions.

Step 1: Find Total Marks

First, we will find the total marks using the SUM function in excelThe SUM function in excel adds the numerical values in a range of cells. Being categorized under the Math and Trigonometry function, it is entered by typing “=SUM” followed by the values to be summed. The values supplied to the function can be numbers, cell references or ranges.read more.

VBA Function Example 1-1

Then, press the “Enter” key to get the result.

VBA Function Example 1-2

Drag the formula to the rest of the cells.

VBA Function Example 1-3

Now, to find out the result (passed, failed, or essential repeat), the criteria set by the school is that.

  • Suppose a student has scored more than or equal to 200 as total marks out of 500. In addition, suppose they have also not failed in any subject (scored more than 32 in each subject), a student is passed.
  • If the student scored more than or equal to 200 but failed in 1 or 2 subjects, then a student will get “Essential Repeat” in those subjects.
  • If the student has scored either less than 200 or fails in 3 or more subjects, then the student failed.
Step 2: Create ResultOfStudent Function

To create a function named ‘ResultOfStudent,’ we need to open “Visual Basic Editor” by using any of the methods below:

  • Using the Developer tab excel.Enabling the developer tab in excel can help the user perform various functions for VBA, Macros and Add-ins like importing and exporting XML, designing forms, etc. This tab is disabled by default on excel; thus, the user needs to enable it first from the options menu.read more

VBA Function Example 1-4

If the Developer tab is not available in MS Excel, then we can get that by using the following steps:

  • Right-click anywhere on the ribbon. Then, choose to Customize the Ribbon in excelRibbons in Excel 2016 are designed to help you easily locate the command you want to use. Ribbons are organized into logical groups called Tabs, each of which has its own set of functions.read more.

VBA Function Example 1-5

When we choose this command, the “Excel Options” dialog box opens.

  • We need to check the box for “Developer” to get the tab.

VBA Function Example 1-6

  • Using the shortcut key, Alt+F11.

VBA Function Shortcut Key

  • When we open the VBA editorThe Visual Basic for Applications Editor is a scripting interface. These scripts are primarily responsible for the creation and execution of macros in Microsoft software.read more, we need to insert the module by going to the Insert menu and choosing a module.

VBA Function Example 1-7

  • We need to paste the following code into the module.
Function ResultOfStudents(Marks As Range) As String

Dim mycell As Range
Dim Total As Integer
Dim CountOfFailedSubject As Integer

For Each mycell In Marks
Total = Total + mycell.Value

If mycell.Value < 33 Then
CountOfFailedSubject = CountOfFailedSubject + 1
End If

Next mycell
If Total >= 200 And CountOfFailedSubject <= 2 And CountOfFailedSubject > 0 Then
ResultOfStudents = "Essential Repeat"

ElseIf Total >= 200 And CountOfFailedSubject = 0 Then
ResultOfStudents = "Passed"

Else
ResultOfStudents = "Failed"
End If

End Function

VBA Function Example 1-8

The above function returns the result for a student.

We need to understand how this code is working.

The first statement, ‘Function ResultOfStudents(Marks As Range) As String,’ declares a function named ‘ResultOfStudents’ that will accept a range as input for marks and return the result as a string.

Dim mycell As Range
Dim Total As Integer
Dim CountOfFailedSubject As Integer

These three statements declare variables, i.e.,

  • ‘myCell’ as a Range,
  • ‘Total’ as Integer (to store total marks scored by a student),
  • ‘CountOfFailedSubject’ is an Integer (to store the number of subjects a student has failed).
For Each mycell In Marks
Total = Total + mycell.Value

If mycell.Value < 33 Then
CountOfFailedSubject = CountOfFailedSubject + 1
End If

Next mycell

This code checks for every cell in the ‘Marks’ range. It adds the value of every cell in the ‘Total’ variable. If the cell’s value is less than 33, add 1 to the ‘CountOfFailedSubject’ variable.

If Total >= 200 And CountOfFailedSubject <= 2 And CountOfFailedSubject > 0 Then
ResultOfStudents = "Essential Repeat"

ElseIf Total >= 200 And CountOfFailedSubject = 0 Then
ResultOfStudents = "Passed"

Else
ResultOfStudents = "Failed"
End If

This code checks the value of ‘Total’ and ‘CountOfFailedSubject’ and passes the Essential Report,’ ‘Passed,’ or ‘Failed’ to the ‘ResultOfStudents.’

Step 3: Apply ResultOfStudents Function to Get Result

ResultOfStudents function takes marks, i.e., selecting 5 marks scored by the student.

VBA Function Example 1-10

Now, select the range of cells, B2: F2.

Example 1-11

Drag the formula to the rest of the cells.

Example 1-13

Step 4: Create ‘GradeForStudent’ Function to get Grades

Now to find out the grade for the student, we will create one more function named ‘GradeForStudent.’

The code would be:

Function GradeForStudent(TotalMarks As Integer, Result As String) As String

If TotalMarks > 440 And TotalMarks <= 500 And ((Result = "Passed" Or Result = "Essential Repeat") 
Or Result = "Essential Repeat") Then GradeForStudent = "A"

ElseIf TotalMarks > 380 And TotalMarks <= 440 And (Result = "Passed" Or Result = "Essential Repeat") Then
GradeForStudent = "B"

ElseIf TotalMarks > 320 And TotalMarks <= 380 And (Result = "Passed" Or Result = "Essential Repeat") Then
GradeForStudent = "C"

ElseIf TotalMarks > 260 And TotalMarks <= 320 And (Result = "Passed" Or Result = "Essential Repeat") Then
GradeForStudent = "D"

ElseIf TotalMarks >= 200 And TotalMarks <= 260 And (Result = "Passed" Or Result = "Essential Repeat") Then
GradeForStudent = "E"

ElseIf TotalMarks < 200 Or Result = "Failed" Then
GradeForStudent = "F"

End If

End Function

This function assigns a ‘Grade’ to the student based on the ‘Total Marks’ and ‘Result.’

VBA Function Example 1-9

We need to write the formula and open the brackets in cell H2. Press Ctrl+Shift+A to find out the arguments.

VBA Function Shortcut arguments

The GradeForStudent function takes Total marks (sum of marks) and the result of the student as an argument to calculate the grade.

Example 1-14

Now, select the individual cells, G2 and H2.

Example 1-15

Now, we need to press Ctrl+D after selecting the cells to copy down the formulas.

Example 1-16

We can highlight the values of less than 33 with the red background color to find out the subjects in which the student failed.

Example 1-17

Recommended Articles

This article is a guide to VBA Functions. Here, we discuss creating custom functions using VBA code, practical examples, and a downloadable Excel template. You may learn more about VBA from the following articles:-

  • VBA IIFThe «VBA IIF» condition evaluates the supplied expression or logical test and returns TRUE or FALSE as a result.read more
  • SUMIF With VLOOKUPSUMIF is used to sum cells based on some condition, which takes arguments of range, criteria, or condition, and cells to sum. When there is a large amount of data available in multiple columns, we can use VLOOKUP as the criteria.read more
  • Excel SUMIF Between Two DatesWhen we wish to work with data that has serial numbers with different dates and the condition to sum the values is based between two dates, we use Sumif between two dates. read more
  • Excel VBA Delete RowIn VBA, to delete the command and to delete any rows together, the trick is that we give a single row reference if we need to delete a single row. However, for the multiple columns, we can provide numerous row references.read more

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

With VBA, you can create a custom Function (also called a User Defined Function) that can be used in the worksheets just like regular functions.

These are helpful when the existing Excel functions are not enough. In such cases, you can create your own custom User Defined Function (UDF) to cater to your specific needs.

In this tutorial, I’ll cover everything about creating and using custom functions in VBA.

If you’re interested in learning VBA the easy way, check out my Online Excel VBA Training.

What is a Function Procedure in VBA?

A Function procedure is a VBA code that performs calculations and returns a value (or an array of values).

Using a Function procedure, you can create a function that you can use in the worksheet (just like any regular Excel function such as SUM or VLOOKUP).

When you have created a Function procedure using VBA, you can use it in three ways:

  1. As a formula in the worksheet, where it can take arguments as inputs and returns a value or an array of values.
  2. As a part of your VBA subroutine code or another Function code.
  3. In Conditional Formatting.

While there are already 450+ inbuilt Excel functions available in the worksheet, you may need a custom function if:

  • The inbuilt functions can’t do what you want to get done. In this case, you can create a custom function based on your requirements.
  • The inbuilt functions can get the work done but the formula is long and complicated. In this case, you can create a custom function that is easy to read and use.

Note that custom functions created using VBA can be significantly slower than the inbuilt functions. Hence, these are best suited for situations where you can’t get the result using the inbuilt functions.

Function Vs. Subroutine in VBA

A ‘Subroutine’ allows you to execute a set of code while a ‘Function’ returns a value (or an array of values).

To give you an example, if you have a list of numbers (both positive and negative), and you want to identify the negative numbers, here is what you can do with a function and a subroutine.

A subroutine can loop through each cell in the range and can highlight all the cells that have a negative value in it. In this case, the subroutine ends up changing the properties of the range object (by changing the color of the cells).

With a custom function, you can use it in a separate column and it can return a TRUE if the value in a cell is negative and FALSE if it’s positive. With a function, you can not change the object’s properties. This means that you can not change the color of the cell with a function itself (however, you can do it using conditional formatting with the custom function).

When you create a User Defined Function (UDF) using VBA, you can use that function in the worksheet just like any other function. I will cover more on this in the ‘Different Ways of Using a User Defined Function in Excel’ section.

Creating a Simple User Defined Function in VBA

Let me create a simple user-defined function in VBA and show you how it works.

The below code creates a function that will extract the numeric parts from an alphanumeric string.

Function GetNumeric(CellRef As String) as Long
Dim StringLength As Integer
StringLength = Len(CellRef)
For i = 1 To StringLength
If IsNumeric(Mid(CellRef, i, 1)) Then Result = Result & Mid(CellRef, i, 1)
Next i
GetNumeric = Result
End Function

When you have the above code in the module, you can use this function in the workbook.

Below is how this function – GetNumeric – can be used in Excel.

Using a User Defined Function in Excel - GetNumeric

Now before I tell you how this function is created in VBA and how it works, there are a few things you should know:

  • When you create a function in VBA, it becomes available in the entire workbook just like any other regular function.
  • When you type the function name followed by the equal to sign, Excel will show you the name of the function in the list of matching functions. In the above example, when I entered =Get, Excel showed me a list that had my custom function.

I believe this is a good example when you can use VBA to create a simple-to-use function in Excel. You can do the same thing with a formula as well (as shown in this tutorial), but that becomes complicated and hard to understand. With this UDF, you only need to pass one argument and you get the result.

Anatomy of a User Defined Function in VBA

In the above section, I gave you the code and showed you how the UDF function works in a worksheet.

Now let’s deep dive and see how this function is created. You need to place the below code in a module in the VB Editor. I cover this topic in the section – ‘Where to put the VBA Code for a User-Defined Function’.

Function GetNumeric(CellRef As String) as Long
' This function extracts the numeric part from the string
Dim StringLength As Integer
StringLength = Len(CellRef)
For i = 1 To StringLength
If IsNumeric(Mid(CellRef, i, 1)) Then Result = Result & Mid(CellRef, i, 1)
Next i
GetNumeric = Result
End Function

The first line of the code starts with the word – Function.

This word tells VBA that our code is a function (and not a subroutine). The word Function is followed by the name of the function – GetNumeric. This is the name that we will be using in the worksheet to use this function.

  • The name of the function cannot have spaces in it. Also, you can’t name a function if it clashes with the name of a cell reference. For example, you can not name the function ABC123 as it also refers to a cell in Excel worksheet.
  • You shouldn’t give your function the same name as that of an existing function. If you do this, Excel would give preference to the in-built function.
  • You can use an underscore if you want to separate words. For example, Get_Numeric is an acceptable name.

The function name is followed by some arguments in parenthesis. These are the arguments that our function would need from the user. These are just like the arguments that we need to supply to Excel’s inbuilt functions. For example in a COUNTIF function, there are two arguments (range and criteria)

Arguments in a user defined function in VBA

Within the parenthesis, you need to specify the arguments.

In our example, there is only one argument – CellRef.

It’s also a good practice to specify what kind of argument the function expects. In this example, since we will be feeding the function a cell reference, we can specify the argument as a ‘Range’ type. If you don’t specify a data type, VBA would consider it to be a variant (which means you can use any data type).

Argument defined as range in the user defined function

If you have more than one arguments, you can specify those in the same parenthesis – separated by a comma. We will see later in this tutorial on how to use multiple arguments in a user-defined function.

Note that the function is specified as the ‘String’ data type. This would tell VBA that the result of the formula would be of the String data type.

While I can use a numeric data type here (such as Long or Double), doing that would limit the range of numbers it can return. If I have a 20 number long string that I need to extract from the overall string, declaring the function as a Long or Double would give an error (as the number would be out of its range). Hence I have kept the function output data type as String.

Defining the Function Output Data type in the custom function

The second line of the code – the one in green that starts with an apostrophe – is a comment. When reading the code, VBA ignores this line. You can use this to add a description or a detail about the code.

Comment in the User Defined Function in Excel VBA

The third line of the code declares a variable ‘StringLength’ as an Integer data type. This is the variable where we store the value of the length of the string that is being analyzed by the formula.

The fourth line declares the variable Result as a String data type. This is the variable where we will extract the numbers from the alphanumeric string.

Declaring Variables in the UDF custom function in VBA

The fifth line assigns the length of the string in the input argument to the ‘StringLength’ variable. Note that ‘CellRef’ refers to the argument that will be given by the user while using the formula in the worksheet (or using it in VBA – which we will see later in this tutorial).

Assigning length of the string to a variable

Sixth, seventh, and eighth lines are the part of the For Next loop. The loop runs for as many times as many characters are there in the input argument. This number is given by the LEN function and is assigned to the ‘StringLength’ variable.

So the loop runs from ‘1 to Stringlength’.

Within the loop, the IF statement analyzes each character of the string and if it’s numeric, it adds that numeric character to the Result variable. It uses the MID function in VBA to do this.

For Next Loop in the User Defined Function

The second last line of the code assigns the value of the result to the function. It’s this line of code that ensures that the function returns the ‘Result’ value back in the cell (from where it’s called).Assigning Result value to the custom function

The last line of the code is End Function. This is a mandatory line of code that tells VBA that the function code ends here.

End Function as the last line of VBA code

The above code explains the different parts of a typical custom function created in VBA. In the following sections, we will deep dive into these elements and also see the different ways to execute the VBA function in Excel.

Arguments in a User Defined Function in VBA

In the above examples, where we created a user-defined function to get the numeric part from an alphanumeric string (GetNumeric), the function was designed to take one single argument.

In this section, I will cover how to create functions that take no argument to the ones that take multiple arguments (required as well as optional arguments).

Creating a Function in VBA without Any Arguments

In Excel worksheet, we have several functions that take no arguments (such as RAND, TODAY, NOW).

These functions are not dependent on any input arguments. For example, the TODAY function would return the current date and the RAND function would return a random number between 0 and 1.

You can create such similar function in VBA as well.

Below is the code that will give you the name of the file. It doesn’t take any arguments as the result it needs to return is not dependent on any argument.

Function WorkbookName() As String
WorkbookName = ThisWorkbook.Name
End Function

The above code specifies the function’s result as a String data type (as the result we want is the file name – which is a string).

This function assigns the value of  ‘ThisWorkbook.Name’ to the function, which is returned when the function is used in the worksheet.

If the file has been saved, it returns the name with the file extension, else it simply gives the name.

The above has one issue though.

If the file name changes, it wouldn’t automatically update. Normally a function refreshes whenever there is a change in the input arguments. But since there are no arguments in this function, the function doesn’t recalculate (even if you change the name of the workbook, close it and then reopen again).

If you want, you can force a recalculation by using the keyboard shortcut – Control + Alt + F9.

To make the formula recalculate whenever there is a change in the worksheet, you need to a line of code to it.

The below code makes the function recalculate whenever there is a change in the worksheet (just like other similar worksheet functions such as TODAY or RAND function).

Function WorkbookName() As String
Application.Volatile True
WorkbookName = ThisWorkbook.Name
End Function

Now, if you change the workbook name, this function would update whenever there is any change in the worksheet or when you reopen this workbook.

Creating a Function in VBA with One Argument

In one of the sections above, we have already seen how to create a function that takes only one argument (the GetNumeric function covered above).

Let’s create another simple function that takes only one argument.

Function created with the below code would convert the referenced text into uppercase. Now we already have a function for it in Excel, and this function is just to show you how it works. If you have to do this, it’s better to use the inbuilt UPPER function.

Function ConvertToUpperCase(CellRef As Range)
ConvertToUpperCase = UCase(CellRef)
End Function

This function uses the UCase function in VBA to change the value of the CellRef variable. It then assigns the value to the function ConvertToUpperCase.

Since this function takes an argument, we don’t need to use the Application.Volatile part here. As soon as the argument changes, the function would automatically update.

Creating a Function in VBA with Multiple Arguments

Just like worksheet functions, you can create functions in VBA that takes multiple arguments.

The below code would create a function that will extract the text before the specified delimiter. It takes two arguments – the cell reference that has the text string, and the delimiter.

Function GetDataBeforeDelimiter(CellRef As Range, Delim As String) as String
Dim Result As String
Dim DelimPosition As Integer
DelimPosition = InStr(1, CellRef, Delim, vbBinaryCompare) - 1
Result = Left(CellRef, DelimPosition)
GetDataBeforeDelimiter = Result
End Function

When you need to use more than one argument in a user-defined function, you can have all the arguments in the parenthesis, separated by a comma.

Note that for each argument, you can specify a data type. In the above example, ‘CellRef’ has been declared as a range datatype and ‘Delim’ has been declared as a String data type. If you don’t specify any data type, VBA considers these are a variant data type.

When you use the above function in the worksheet, you need to give the cell reference that has the text as the first argument and the delimiter character(s) in double quotes as the second argument.

It then checks for the position of the delimiter using the INSTR function in VBA. This position is then used to extract all the characters before the delimiter (using the LEFT function).

Finally, it assigns the result to the function.

This formula is far from perfect. For example, if you enter a delimiter that is not found in the text, it would give an error. Now you can use the IFERROR function in the worksheet to get rid of the errors, or you can use the below code that returns the entire text when it can’t find the delimiter.

Function GetDataBeforeDelimiter(CellRef As Range, Delim As String) as String
Dim Result As String
Dim DelimPosition As Integer
DelimPosition = InStr(1, CellRef, Delim, vbBinaryCompare) - 1
If DelimPosition < 0 Then DelimPosition = Len(CellRef)
Result = Left(CellRef, DelimPosition)
GetDataBeforeDelimiter = Result
End Function

We can further optimize this function.

If you enter the text (from which you want to extract the part before the delimiter) directly in the function, it would give you an error. Go ahead.. try it!

This happens as we have specified the ‘CellRef’ as a range data type.

Or, if you want the delimiter to be in a cell and use the cell reference instead of hard coding it in the formula, you can’t do that with the above code. It’s because the Delim has been declared as a string datatype.

If you want the function to have the flexibility to accept direct text input or cell references from the user, you need to remove the data type declaration. This would end up making the argument as a variant data type, which can take any type of argument and process it.

The below code would do this:

Function GetDataBeforeDelimiter(CellRef, Delim) As String
Dim Result As String
Dim DelimPosition As Integer
DelimPosition = InStr(1, CellRef, Delim, vbBinaryCompare) - 1
If DelimPosition < 0 Then DelimPosition = Len(CellRef)
Result = Left(CellRef, DelimPosition)
GetDataBeforeDelimiter = Result
End Function

Creating a Function in VBA with Optional Arguments

There are many functions in Excel where some of the arguments are optional.

For example, the legendary VLOOKUP function has 3 mandatory arguments and one optional argument.

Optional Argument in the VLOOKUP function

An optional argument, as the name suggests, is optional to specify. If you don’t specify one of the mandatory arguments, your function is going to give you an error, but if you don’t specify the optional argument, your function would work.

But optional arguments are not useless. They allow you to choose from a range of options.

For example, in the VLOOKUP function, if you don’t specify the fourth argument, VLOOKUP does an approximate lookup and if you specify the last argument as FALSE (or 0), then it does an exact match.

Remember that the optional arguments must always come after all the required arguments. You can’t have optional arguments at the beginning.

Now let’s see how to create a function in VBA with optional arguments.

Function with Only an Optional Argument

As far as I know, there is no inbuilt function that takes optional arguments only (I can be wrong here, but I can’t think of any such function).

But we can create one with VBA.

Below is the code of the function that will give you the current date in the dd-mm-yyyy format if you don’t enter any argument (i.e. leave it blank), and in “dd mmmm, yyyy” format if you enter anything as the argument (i.e., anything so that the argument is not blank).

Function CurrDate(Optional fmt As Variant)
Dim Result
If IsMissing(fmt) Then
CurrDate = Format(Date, "dd-mm-yyyy")
Else
CurrDate = Format(Date, "dd mmmm, yyyy")
End If
End Function

Note that the above function uses ‘IsMissing’ to check whether the argument is missing or not. To use the IsMissing function, your optional argument must be of the variant data type.

The above function works no matter what you enter as the argument. In the code, we only check if the optional argument is supplied or not.

You can make this more robust by taking only specific values as arguments and showing an error in rest of the cases (as shown in the below code).

Function CurrDate(Optional fmt As Variant)
Dim Result
If IsMissing(fmt) Then
CurrDate = Format(Date, "dd-mm-yyyy")
ElseIf fmt = 1 Then
CurrDate = Format(Date, "dd mmmm, yyyy")
Else
CurrDate = CVErr(xlErrValue)
End If
End Function

The above code creates a function that shows the date in the “dd-mm-yyyy” format if no argument is supplied, and in “dd mmmm,yyyy” format when the argument is 1. It gives an error in all other cases.

Function with Required as well as Optional Arguments

We have already seen a code that extracts the numeric part from a string.

Now let’s have a look at a similar example that takes both required as well as optional arguments.

The below code creates a function that extracts the text part from a string. If the optional argument is TRUE, it gives the result in uppercase, and if the optional argument is FALSE or is omitted, it gives the result as is.

Function GetText(CellRef As Range, Optional TextCase = False) As String
Dim StringLength As Integer
Dim Result As String
StringLength = Len(CellRef)
For i = 1 To StringLength
If Not (IsNumeric(Mid(CellRef, i, 1))) Then Result = Result & Mid(CellRef, i, 1)
Next i
If TextCase = True Then Result = UCase(Result)
GetText = Result
End Function

Note that in the above code, we have initialized the value of ‘TextCase’ as False (look within the parenthesis in the first line).

By doing this, we have ensured that the optional argument starts with the default value, which is FALSE. If the user specifies the value as TRUE, the function returns the text in upper case, and if the user specifies the optional argument as FALSE or omits it, then the text returned is as is.

Creating a Function in VBA with an Array as the Argument

So far we have seen examples of creating a function with Optional/Required arguments – where these arguments were a single value.

You can also create a function that can take an array as the argument. In Excel worksheet functions, there are many functions that take array arguments, such as SUM, VLOOKUP, SUMIF, COUNTIF, etc.

Below is the code that creates a function that gives the sum of all the even numbers in the specified range of the cells.

Function AddEven(CellRef as Range)
 Dim Cell As Range
 For Each Cell In CellRef
 If IsNumeric(Cell.Value) Then
 If Cell.Value Mod 2 = 0 Then
 Result = Result + Cell.Value
 End If
 End If
 Next Cell
 AddEven = Result
 End Function

You can use this function in the worksheet and provide the range of cells that have the numbers as the argument. The function would return a single value – the sum of all the even numbers (as shown below).

Creating a User Defined Function with an array argument

In the above function, instead of a single value, we have supplied an array (A1:A10). For this to work, you need to make sure your data type of the argument can accept an array.

In the code above, I specified the argument CellRef as Range (which can take an array as the input). You can also use the variant data type here.

In the code, there is a For Each loop that goes through each cell and checks if it’s a number of not. If it isn’t, nothing happens and it moves to the next cell. If it’s a number, it checks if it’s even or not (by using the MOD function).

In the end, all the even numbers are added and teh sum is assigned back to the function.

Creating a Function with Indefinite Number of Arguments

While creating some functions in VBA, you may not know the exact number of arguments that a user wants to supply. So the need is to create a function that can accept as many arguments are supplied and use these to return the result.

An example of such worksheet function is the SUM function. You can supply multiple arguments to it (such as this):

=SUM(A1,A2:A4,B1:B20)

The above function would add the values in all these arguments. Also, note that these can be a single cell or an array of cells.

You can create such a function in VBA by having the last argument (or it could be the only argument) as optional. Also, this optional argument should be preceded by the keyword ‘ParamArray’.

‘ParamArray’ is a modifier that allows you to accept as many arguments as you want. Note that using the word ParamArray before an argument makes the argument optional. However, you don’t need to use the word Optional here.

Now let’s create a function that can accept an arbitrary number of arguments and would add all the numbers in the specified arguments:

Function AddArguments(ParamArray arglist() As Variant)
For Each arg In arglist
AddArguments = AddArguments + arg
Next arg
End Function

The above function can take any number of arguments and add these arguments to give the result.

Function with paramarray

Note that you can only use a single value, a cell reference, a boolean, or an expression as the argument. You can not supply an array as the argument. For example, if one of your arguments is D8:D10, this formula would give you an error.

If you want to be able to use both multi-cell arguments you need to use the below code:

Function AddArguments(ParamArray arglist() As Variant)
For Each arg In arglist
For Each Cell In arg
AddArguments = AddArguments + Cell
Next Cell
Next arg
End Function

Note that this formula works with multiple cells and array references, however, it can not process hardcoded values or expressions. You can create a more robust function by checking and treating these conditions, but that’s not the intent here.

The intent here is to show you how ParamArray works so you can allow an indefinite number of arguments in the function. In case you want a better function than the one created by the above code, use the SUM function in the worksheet.

Creating a Function that Returns an Array

So far we have seen functions that return a single value.

With VBA, you can create a function that returns a variant that can contain an entire array of values.

Array formulas are also available as inbuilt functions in Excel worksheets. If you’re familiar with array formulas in Excel, you would know that these are entered using Control + Shift + Enter (instead of just the Enter). You can read more about array formulas here. If you don’t know about array formulas, don’t worry, keep reading.

Let’s create a formula that returns an array of three numbers (1,2,3).

The below code would do this.

Function ThreeNumbers() As Variant
Dim NumberValue(1 To 3)
NumberValue(1) = 1
NumberValue(2) = 2
NumberValue(3) = 3
ThreeNumbers = NumberValue
End Function

In the above code, we have specified the ‘ThreeNumbers’ function as a variant. This allows it to hold an array of values.

The variable ‘NumberValue’ is declared as an array with 3 elements. It holds the three values and assigns it to the ‘ThreeNumbers’ function.

You can use this function in the worksheet by entering the function and hitting the Control + Shift + Enter key (hold the Control and the Shift keys and then press Enter).

Creating a function in VBA that returns an array

When you do this, it will return 1 in the cell, but in reality, it holds all the three values. To check this, use the below formula:

=MAX(ThreeNumbers())

Use the above function with Control + Shift + Enter. You will notice that the result is now 3, as it is the largest values in the array returned by the Max function, which gets the three numbers as the result of our user-defined function – ThreeNumbers.

You can use the same technique to create a function that returns an array of Month Names as shown by the below code:

Function Months() As Variant
Dim MonthName(1 To 12)
MonthName(1) = "January"
MonthName(2) = "February"
MonthName(3) = "March"
MonthName(4) = "April"
MonthName(5) = "May"
MonthName(6) = "June"
MonthName(7) = "July"
MonthName(8) = "August"
MonthName(9) = "September"
MonthName(10) = "October"
MonthName(11) = "November"
MonthName(12) = "December"
Months = MonthName
End Function

Now when you enter the function =Months() in Excel worksheet and use Control + Shift + Enter, it will return the entire array of month names. Note that you see only January in the cell as that is the first value in the array. This does not mean that the array is only returning one value.

Creating a function in VBA that returns an array of month names

To show you the fact that it is returning all the values, do this – select the cell with the formula, go to the formula bar, select the entire formula and press F9. This will show you all the values that the function returns.

Array formula in VBA - All contents with F9

You can use this by using the below INDEX formula to get a list of all the month names in one go.

=INDEX(Months(),ROW())

Array formula in VBA - with Index Function

Now if you have a lot of values, it’s not a good practice to assign these values one by one (as we have done above). Instead, you can use the Array function in VBA.

So the same code where we create the ‘Months’ function would become shorter as shown below:

Function Months() As Variant
Months = Array("January", "February", "March", "April", "May", "June", _
"July", "August", "September", "October", "November", "December")
End Function

The above function uses the Array function to assign the values directly to the function.

Note that all the functions created above return a horizontal array of values. This means that if you select 12 horizontal cells (let’s say A1:L1), and enter the =Months() formula in cell A1, it will give you all the month names.

Months names in horizontal cells

But what if you want these values in a vertical range of cells.

You can do this by using the TRANSPOSE formula in the worksheet.

Simply select 12 vertical cells (contiguous), and enter the below formula.

getting a vertical array of values from a VBA function

Understanding the Scope of a User Defined Function in Excel

A function can have two scopes – Public or Private.

  • A Public scope means that the function is available for all the sheets in the workbook as well as all the procedures (Sub and Function) across all modules in the workbook. This is useful when you want to call a function from a subroutine (we will see how this is done in the next section).
  • A Private scope means that the function is available only in the module in which it exists. You can’t use it in other modules. You also won’t see it in the list of functions in the worksheet. For example, if your Function name is ‘Months()’, and you type function in Excel (after the = sign), it will not show you the function name. You can, however, still, use it if you enter the formula name.

If you don’t specify anything, the function is a Public function by default.

Below is a function that is a Private function:

Private Function WorkbookName() As String
WorkbookName = ThisWorkbook.Name
End Function

You can use this function in the subroutines and the procedures in the same modules, but can’t use it in other modules. This function would also not show up in the worksheet.

The below code would make this function Public. It will also show up in the worksheet.

Function WorkbookName() As String
WorkbookName = ThisWorkbook.Name
End Function

Different Ways of Using a User Defined Function in Excel

Once you have created a user-defined function in VBA, you can use it in many different ways.

Let’s first cover how to use the functions in the worksheet.

Using UDFs in Worksheets

We have already seen examples of using a function created in VBA in the worksheet.

All you need to do is enter the functions name, and it shows up in the intellisense.

Public VBA function used in Worksheet

Note that for the function to show up in the worksheet, it must be a Public function (as explained in the section above).

You can also use the Insert Function dialog box to insert the user defined function (using the steps below). This would work only for functions that are Public.

The above steps would insert the function in the worksheet. It also displays a Function Arguments dialog box that will give you details on the arguments and the result.

Information dialog box when you insert the Function

You can use a user defined function just like any other function in Excel. This also means that you can use it with other inbuilt Excel functions. For example. the below formula would give the name of the workbook in upper case:

=UPPER(WorkbookName())

Using User Defined Functions in VBA Procedures and Functions

When you have created a function, you can use it in other sub-procedures as well.

If the function is Public, it can be used in any procedure in the same or different module. If it’s Private, it can only be used in the same module.

Below is a function that returns the name of the workbook.

Function WorkbookName() As String 
WorkbookName = ThisWorkbook.Name 
End Function

The below procedure call the function and then display the name in a message box.

Sub ShowWorkbookName()
MsgBox WorkbookName
End Sub

You can also call a function from another function.

In the below codes, the first code returns the name of the workbook, and the second one returns the name in uppercase by calling the first function.

Function WorkbookName() As String
WorkbookName = ThisWorkbook.Name
End Function
Function WorkbookNameinUpper()
WorkbookNameinUpper = UCase(WorkbookName)
End Function

Calling a User Defined Function from Other Workbooks

If you have a function in a workbook, you can call this function in other workbooks as well.

There are multiple ways to do this:

  1. Creating an Add-in
  2. Saving function in the Personal Macro Workbook
  3. Referencing the function from another workbook.

Creating an Add-in

By creating and installing an add-in, you will have the custom function in it available in all the workbooks.

Suppose you have created a custom function – ‘GetNumeric’ and you want it in all the workbooks. To do this, create a new workbook and have the function code in a module in this new workbook.

Now follow the steps below to save it as an add-in and then install it in Excel.

Now the add-in has been activated.

Now you can use the custom function in all the workbooks.

Saving the Function in Personal Macro Workbook

A Personal Macro Workbook is a hidden workbook in your system that opens whenever you open the Excel application.

It’s a place where you can store macro codes and then access these macros from any workbook. It’s a great place to store those macros that you want to use often.

By default, there is no personal macro workbook in your Excel. You need to create it by recording a macro and saving it in the Personal macro workbook.

You can find the detailed steps on how to create and save macros in the personal macro workbook here.

Referencing the function from another workbook

While the first two methods (creating an add-in and using personal macro workbook) would work in all situations, if you want to reference the function from another workbook, that workbook needs to be open.

Suppose you have a workbook with the name ‘Workbook with Formula’, and it has the function with the name ‘GetNumeric’.

To use this function in another workbook (while the Workbook with Formula is open), you can use the below formula:

=’Workbook with Formula’!GetNumeric(A1)

The above formula will use the user defined function in the Workbook with Formula file and give you the result.

Note that since the workbook name has spaces, you need to enclose it in single quotes.

Using Exit Function Statement VBA

If you want to exit a function while the code is running, you can do that by using the ‘Exit Function’ statement.

The below code would extract the first three numeric characters from an alphanumeric text string. As soon as it gets the three characters, the function ends and returns the result.

Function GetNumericFirstThree(CellRef As Range) As Long
Dim StringLength As Integer
StringLength = Len(CellRef)
For i = 1 To StringLength
If J = 3 Then Exit Function
If IsNumeric(Mid(CellRef, i, 1)) Then
J = J + 1
Result = Result & Mid(CellRef, i, 1)
GetNumericFirstThree = Result
End If
Next i
End Function

The above function checks for the number of characters that are numeric, and when it gets 3 numeric characters, it Exits the function in the next loop.

Debugging a User Defined Function

There are a few techniques you can use while debugging a user-defined function in VBA:

Debugging a Custom Function by Using the Message Box

Use MsgBox function to show a message box with a specific value.

The value you display can be based on what you want to test. For example, if you want to check if the code is getting executed or not, any message would work, and if you want to check whether the loops are working or not, you can display a specific value or the loop counter.

Debugging a Custom Function by  Setting the Breakpoint

Set a breakpoint to be able to go step through each line one at a time. To set a breakpoint, select the line where you want it and press F9, or click on the gray vertical area which is left to the code lines. Any of these methods would insert a breakpoint (you will see a red dot in the gray area).

Setting the breakpoint

Once you have set the breakpoint and you execute the function, it goes till the breakpoint line and then stops. Now you can step through the code using the F8 key. Pressing F8 once moves to the next line in the code.

Debugging a Custom Function by Using Debug.Print in the Code

You can use Debug.Print statement in your code to get the values of the specified variables/arguments in the immediate window.

For example, in the below code, I have used Debug.Print to get the value of two variables – ‘j’ and ‘Result’

Function GetNumericFirstThree(CellRef As Range) As Long
Dim StringLength As Integer
StringLength = Len(CellRef)
For i = 1 To StringLength
If J = 3 Then Exit Function
If IsNumeric(Mid(CellRef, i, 1)) Then
 J = J + 1
 Result = Result & Mid(CellRef, i, 1)
 Debug.Print J, Result
 GetNumericFirstThree = Result
End If
Next i
End Function

When this code is executed, it shows the following in the immediate window.

Immediate Window result when creating a custom function in VBA Excel

Excel Inbuilt Functions Vs. VBA User Defined Function

There are few strong benefits of using Excel in-built functions over custom functions created in VBA.

  • Inbuilt functions are a lot faster than the VBA functions.
  • When you create a report/dashboard using VBA functions, and you send it to a client/colleague, they wouldn’t have to worry about whether the macros are enabled or not. In some cases, clients/customers get scared by seeing a warning in the yellow bar (which simply asks them to enable macros).
  • With inbuilt Excel functions, you don’t need to worry about file extensions. If you have macros or user-defined functions in the workbook, you need to save it in .xlsm.

While there are many strong reasons to use Excel in-built functions, in a few cases, you’re better off using a user-defined function.

  • It’s better to use a user-defined function if your inbuilt formula is huge and complicated. This becomes even more relevant when you need someone else to update the formulas. For example, if you have a huge formula made up of many different functions, even changing a reference to a cell can be tedious and error-prone. Instead, you can create a custom function that only takes one or two arguments and does all the heavy lifting the backend.
  • When you have to get something done that can not be done by Excel inbuilt functions. An example of this can be when you want to extract all the numeric characters from a string. In such cases, the benefit of using a user-defined function gar outweighs its negatives.

Where to put the VBA Code for a User-Defined Function

When creating a custom function, you need to put the code in the code window for the workbook in which you want the function.

Below are the steps to put the code for the ‘GetNumeric’ function in the workbook.

  1. Go to the Developer tab.IF Then Else in Excel VBA - Developer Tab in ribbon
  2. Click on the Visual Basic option. This will open the VB editor in the backend.Click on Visual Basic
  3. In the Project Explorer pane in the VB Editor, right-click on any object for the workbook in which you want to insert the code. If you don’t see the Project Explorer go to the View tab and click on Project Explorer.
  4. Go to Insert and click on Module. This will insert a module object for your workbook.Saving a Custom Function code in the module
  5. Copy and paste the code in the module window.User Defined function in the module code window

You May Also Like the Following Excel VBA Tutorials:

  • Working with Cells and Ranges in Excel VBA.
  • Working with Worksheets in Excel VBA.
  • Working with Workbooks using VBA.
  • How to use Loops in Excel VBA.
  • Excel VBA Events – An Easy (and Complete) Guide
  • Using IF Then Else Statements in VBA.
  • How to Record a Macro in Excel.
  • How to Run a Macro in Excel.
  • How to Sort Data in Excel using VBA (A Step-by-Step Guide).
  • Excel VBA InStr Function – Explained with Examples.

Home / VBA / VBA Worksheet Function (Use Excel Functions in a Macro)

Key Notes

  • You can use the WorksheetFunction property to access worksheet functions to use in a macro.

How to use a Worksheet Functions in VBA while Writing a Macro

Use the following steps to use a worksheet function in VBA.

  • First, specify the cell where you want to insert the values returned by the function.
    1-worksheet-function-in-vba
  • After that, use an equal sign (=) and type Application.WorksheetFunction (as you can already in the Excel application, you can only use WorksheetFunction).
    2-use-an-equal-sign
  • Next, you need to enter a dot (.), and the moment you do that, you’ll get a list of functions that you have in the worksheet.
    3-you-need-to-enter-a-dot
  • From here, let’s use the TextJoin function to join text from the cell A1 and B1. Just like that, you use a function in the worksheet; when you enter starting parentheses, it shows you the arguments that you need to specify in the cell.
    4-use-the-textjoin-function
  • As you can see in the above screenshot, it shows you the argument that you need to specify, but not the name of the arguments. So, you need to know the arguments before using them. Here are the arguments that you need to use in TextJoin.
    5-arguement-before-using-testjoin
  • Now, let’s enter arguments in the function.
    6-enter-arguement-in-the-function
    1. delimiter: “ “
    2. ignore_empty: True
    3. text1: Range(“A1”)
    4. text2: Range(“B1”)

Here’s the full code.

Sub MyMacro()

Range("A1") = _
Application.WorksheetFunction.TextJoin _
(" ", True, Range("A2"), Range("A3"))

End Sub

And when you run this macro:

There is a total of 387 worksheet functions that you can use in VBA. But there are a few functions (Example: LEFT) that are not available to use.

Reason? There are In-Built functions in VBA that you can use while writing a VBA code.

Let’s if you want to use a message box to get the value for a function. Lets you want to get the maximum value from the named range “myValues”.

The code would be:

Sub MyMacro()

MsgBox Prompt:=WorksheetFunction.Max(Range("myValues"))

End Sub

And here’s how you get a message box:

Application.WorksheetFunction vs. Application

There are two different ways to refer to a worksheet function. Below are the two different lines of code that perform the same activity.

Sub MyMacro()

MsgBox Prompt:= _
Application.WorksheetFunction.Max(Range("myValues"))

MsgBox Prompt:= _
Application.Max(Range("myValues"))

End Sub

But there’s a benefit to using the second method. It returns an error code instead of showing the error directly.

VBA Function in Excel

VBA Function in Excel (Table of Contents)

  • VBA Function in Excel
  • How to Use VBA Function in Excel?
  • Examples of VBA Function in Excel

VBA Function in Excel

We also have functions in VBA as well which are completely inbuilt in it. Almost all the excel functions can be used VBA as well with almost the same syntax. And if there is any change in the syntax, we will be able to see that also when we are about to use VBA function. To declare a function in VBA, first, open a Private-End procedure and select the data type as per functional need.

Visual Basic

VBA stands for Visual Basic for an application. VBA is normally a programming language of excel which is embedded in an individual Microsoft application i.e. Excel or Access where we can do the automation of several tasks which is also called as “MACRO” in excel. The Visual Basic application comes with several command buttons and other function which makes it easier for the user for automation.

VBA User Defined Function (UDF)

A User-defined function is just a function where we can create our self in VBA for automation purpose.

This user-defined function is nothing but a code module attached to the worksheet where the user will actually type the coding.

How to Use VBA Function in Excel?

In excel we can find the VBA function under “DEVELOPER” tab by default excel does not have this menu. So in order to display it, we need to add this “DEVELOPER” menu manually by following the below steps.

  • Go to File menu. Click on Option menu which has highlighted in Yellow Color.

VBA Function Step 1

  • Once we click on the option we will get the below dialogue box as follows.

VBA Function Step 2

  • Select Customize Ribbon option and we will get the below dialogue box as follows

VBA Function Step 3

  • In customize ribbon option we can see add or remove the ribbon manually. Here we can see that on the “Right-hand side” of the customize ribbon “DEVELOPER” Tab is not checked. Checkmark that “DEVELOPER” Tab and click OK

VBA Function Step 4

  • Once you check mark the “DEVELOPER” Tab it will get added in excel menu which is displayed as follows

VBA Function Step 5

Now we can see that the “Developer” Tab is added and it has the features like VISUAL BASIC, MACROS, etc.

Adding VBA in Excel

In Excel, VBA workbook can be added easily by following the below steps.

  • Open Excel workbook. Use the shortcut key ALT+F11 to open Visual Basic Editor which is also called as VBE in excel shown in the below screenshot

VBA Function Step 6

  • Right-click on your workbook name in the ” Project VBAProject” pane (at the top left corner of the editor window) and select Insert -> Module from the context menu as shown below

VBA Function Step 7

  • Now we can see that new module has been added as MODULE 1 on the left-hand side of the panel.

VBA Function Step 8

  • In the Right-hand side where we can use the UDF function using VBA.

The function of Visual Basic

In Visual Basic, we will use the various function. A function is nothing but a collection of visual basic statements enclosed by start and an end function. This function normally performs a task and then returns controls to the calling code. If it returns the control it will also return a value to the specific code.

VBA Function

Visual basic contains a large number of built-in function like Message Function, String and Text Function, Information Function, a Conversion function, Date and Time, Math and Trig Functions, Financial function

We will see the mostly used VBA function which is listed as follows.

  • Input Box- Which displays an input dialogue box
  • Msg Box- Which displays Message box i.e. alert message box
  • Format- Which applies format for the specific string.
  • Len- Which returns a length of the string
  • Replace – Which will replace the specific string with another string.
  • Is Array- Which will check for the supplied value is an array.
  • Is Date- Which will check for the supplied expression is date format.
  • Is Empty – Which will check for the specific variant is empty or not
  • Is Null – Which will check for the supplied value is null or not
  • Date – Returns the current date.
  • Month – Returns the month number.
  • Now – Returns the current date and time.
  • Year – Returns the current year.

Examples of VBA Function in Excel

VBA Function is very simple to use. Let us now see how to use VBA function in Excel with the help of some examples.

You can download this VBA Function Excel Template here – VBA Function Excel Template

Example #1

Addition of Two Numbers

In this example, we will see how to add two numbers using VBA function by using simple programming language step by step as follows.

  • Open excel workbook. Use shortcut key ALT+F11 to open VBE editor. We get the VBE editor as follows

VBA Example 1-1

  • Go to Insert Menu and select module

VBA Example 1-2

Once we click on the module a new module will be added in a worksheet Where we will write the VBA function coding on the right-hand side of General page.

VBA Example 1-3

Now to get the result of adding two numbers we have to use the below coding as follows

Function addtwo(arg1, arg2)
addtwo = arg1 + arg2
End Function

Here in the above coding, we have named the function as “addtwo” and the coding will be displayed as:

VBA Example 1-4

Now in the excel sheet, we can use the “addtwo” function to add the new number as:

VBA Example 1-5

The Result is:

VBA Example 1-6

Example #2

Date Function

In VBA, date function is a built-in function DATE() which return date and time we will now use the date function to get the date in the particular sheet. In VBA we can use UDF to get the result.

Insert a new Module as we have discussed above in Example 1.

Once we click on the module a new module will be added in the worksheet and on the right-hand side of General page, we will write the VBA function coding.

Sub todayDate()
Range("A1").Value = Date
End Sub

Here in the above coding, we have named the function as “todayDate” and the coding will be displayed as:

VBA Example 2-1

Hit the RUN button or Press F5 to execute the code

VBA Example 2-2

This coding will only return the current date in the mentioned cell name A1 and once we execute, the result will be shown as:

VBA Example 2-3

Example #3

VBA Message Box

Visual basic normally has two message box function

  1. The Msg Box method.
  2. The Msg Box Function.

The MsgBox Method

The MSGBOX method is one of the VBA languages where it displays a msgbox for the given string, it normally has the ok button, so that user can see the MSGBOX and continue with the specified task.

The MsgBox Function

The MSGBOX Function which returns value normally this MSGBOX function will be a question type like Yes or No or Abort or Continue.

We will see both the MSG box with the below examples as follows.

Msg Box method Example:

Insert a new Module as we have discussed above in Example 1.

Once we click on the module a new module will be added in the worksheet and on the right-hand side of General page, we will write the VBA function coding.

Sub Firstmsg()
MsgBox "Hello"
End Sub

In the below screenshot, we have written coding to display the MSG BOX as Hello.

VBA Example 3-1

Hit the RUN button or Press F5 to execute the code.

VBA Example 3-2

We will get the below output.

VBA Example 3-3

We can see the HELLO message which comes from the MSG box.

Msg Box Function Example:

In this example, we will see how to use MSG BOX function using vbYesNoCancel

Insert a new Module as we have discussed above in Example 1.

Once we click on the module, a new module will be added in the worksheet and on the right-hand side of General page, where we will write the VBA function coding.

Sub Firstmsg()
MsgBox "Welcome User or Guest?", vbYesNoCancel, "Login?"
End Sub

In the below screenshot, we have written coding to display the MSG BOX. Here in the MSG BOX function, we have given YES or NO option to check the end user is User or Guest.

VBA Example 4-1

Hit the RUN button or Press F5 to execute the code

VBA Example 4-2

After execution, we will get the below MSGBOX as follow

VBA Example 4-3

Things to Remember About VBA Function

  • In VBA we have many built-in functions where it can be used in the automation process.
  • While applying multiple MACROS function make sure that we have assigned a specific key to run it.
  • Name each module in VBA so that to avoid confusion in coding.

Recommended Articles

This has been a guide to Excel VBA Function. Here we discuss how to use VBA Function in Excel along with practical examples and downloadable excel template. You can also go through our other suggested articles –

  1. VBA RGB
  2. VBA CDEC
  3. VBA XML
  4. VBA Month

In This Chapter

Using functions to make your VBA expressions more powerful Using the VBA built-in functions Using Excel worksheet functions in your VBA code Writing custom functions
In previous chapters, I allude to the fact that you can use functions in your VBA expressions. I provide a full explanation in this chapter. Functions can make your VBA code perform some powerful feats, with little or no programming effort required. If you like that idea, this chapter’s for you.

What Is a Function?

All Excel users beyond rank beginners use worksheet functions in their formulas. The most common worksheet function is the SUM function, and you have hundreds of others at your disposal.
A function essentially performs a calculation and returns a single value. The SUM function, of course, returns the sum of a range of values. The same holds true for functions used in your VBA expressions: Each function does its thing and returns a single value.

The functions you use in VBA can come from three sources:

Built-in functions provided by VBA Worksheet functions provided by Excel
Custom functions that you (or someone else) write, using VBA
The rest of this chapter clarifies the differences and (I hope) convinces you of the value of using functions in your VBA code.

Using VBA Functions

VBA provides numerous built-in functions. Some of these functions take arguments and some do not.

VBA function examples

In this section, I present a few examples of using VBA functions in code. In many of these examples, I use the MsgBox function to display a value in a message box. Yes, MsgBox is a VBA function — a rather unusual one, but a function nonetheless. This useful function displays a message in a pop-up dialog box. For more details about the MsgBox function, see Chapter 15.
A workbook that contains all of the examples is available at this topic’s Web site.

Displaying the system date

The first example uses VBA’s Date function to display the current system date in a message box:
tmpD-76_thumb
Notice that the Date function doesn’t use an argument. Unlike worksheet functions, a VBA function with no argument doesn’t require an empty set of parentheses. In fact, if you provide an empty set of parentheses, the VBE will remove them.
To get the system date and time, use the Now function instead of the Date function. Or to get only the time, use the Time function.

Finding a string length

The following procedure uses the VBA Len function, which returns the length of a string. The Len function takes one argument: the string. When you execute this procedure, the message box displays 11 because the argument has 11 characters.
tmpD-77_thumb
Excel also has a function, which you can use in your worksheet formulas. The Excel version and the VBA function work the same.

Displaying the integer part of a number

The following procedure uses the Fix function, which returns the integer portion of a value — the value without any decimal digits:
tmpD-78_thumb
In this case, the message box displays 123.
VBA has a similar function called Int. The difference between Int and Fix is how each deals with negative numbers.
Int returns the first negative integer that’s less than or equal to the argument.
Fix returns the first negative integer that’s greater than or equal to the argument.

Determining a file size

The following Sub procedure displays the size, in bytes, of the Excel executable file. It finds this value by using the FileLen function.
tmpD-79_thumb
Notice that this routine hard codes the filename (that is, it explicitly states the path). Generally, this isn’t a good idea. The file might not be on the C drive, or the Excel folder may have a different name. The following statement shows a better approach:
tmpD-80_thumb
Path is a property of the Application object. It simply returns the name of the folder in which the application (that is, Excel) is installed (without a trailing backslash).

Identifying the type of a selected object

The following procedure uses the Type Name function, which returns the type of the selected object (as a string):
tmpD-81_thumb
This could be a Range, a ChartObject, a TextBox, or any other type of object that can be selected.
The TypeName function is very versatile. You can also use this function to determine the data type of a variable.
VBA functions that do more than return a value
A few VBA functions go above and beyond the call of duty. Rather than simply return a value, these functions have some useful side effects. Table 9-1 lists them.

Table 9-1 Functions with Useful Side Benefits
Function What It Does
MsgBox Displays a handy dialog box containing a message and buttons.
The function returns a code that identifies which button the user
clicks. See Chapter 15 for details.
InputBox Displays a simple dialog box that asks the user for some input.
The function returns whatever the user enters into the dialog
box. I discuss this in Chapter 15.
Function What It Does
Shell Executes another program. The function returns the task ID
(a unique identifier) of the other program (or an error if the
function can’t start the other program).

Discovering VBA functions

How do you find out which functions VBA provides? Good question. The best source is the Excel Visual Basic Help system. I compiled a partial list of functions, which I share with you in Table 9-2. I omitted some of the more specialized or obscure functions.
For complete details on a particular function, type the function name into a VBA module, move the cursor anywhere in the text, and press F1.

Table 9-2 VBA’s Most Useful Built-in Functions
Function What It Does
Abs Returns a number’s absolute value
Array Returns a variant containing an array
Asc Converts the first character of a string to its ASCII value
Atn Returns the arctangent of a number
Choose Returns a value from a list of items
Chr Converts an ANSI value to a string
Cos Returns a number’s cosine
CurDir Returns the current path
Date Returns the current system date
DateAdd Returns a date to which a specified time interval has been
added — for example, one month from a particular date
DateDiff Returns an integer showing the number of specified time intervals
between two dates, for example the number of months between
now and your birthday
DatePart Returns an integer containing the specified part of a given
date — for example, a date’s day of the year
Table 9-2 (continued)
Function What It Does
DateSerial Converts a date to a serial number
DateValue Converts a string to a date
Day Returns the day of the month from a date value
Dir Returns the name of a file or directory that matches a pattern
Erl Returns the line number that caused an error
Err Returns the error number of an error condition
Error Returns the error message that corresponds to an error number
Exp Returns the base of the natural logarithm (e) raised to a power
FileLen Returns the number of bytes in a file
Fix Returns a number’s integer portion
Format Displays an expression in a particular format
GetSetting Returns a value from the Windows registry
Hex Converts from decimal to hexadecimal
Hour Returns the hours portion of a time
InputBox Displays a box to prompt a user for input
InStr Returns the position of a string within another string
Int Returns the integer portion of a number
IPmt Returns the interest payment for an annuity or loan
IsArray Returns True if a variable is an array
IsDate Returns True if an expression is a date
IsEmpty Returns True if a variable has not been initialized
IsError Returns True if an expression is an error value
IsMissing Returns True if an optional argument was not passed to a
procedure
IsNull Returns True if an expression contains no valid data
IsNumeric Returns True if an expression can be evaluated as a number
Function What It Does
IsObject Returns True if an expression references an OLE Automation object
LBound Returns the smallest subscript for a dimension of an array
LCase Returns a string converted to lowercase
Left Returns a specified number of characters from the left of a string
Len Returns the number of characters in a string
Log Returns the natural logarithm of a number to base e
LTrim Returns a copy of a string, with any leading spaces removed
Mid Returns a specified number of characters from a string
Minute Returns the minutes portion of a time value
Month Returns the month from a date value
MsgBox Displays a message box and (optionally) returns a value
Now Returns the current system date and time
RGB Returns a numeric RGB value representing a color
Right Returns a specified number of characters from the right of a string
Rnd Returns a random number between 0 and 1
RTrim Returns a copy of a string, with any trailing spaces removed
Second Returns the seconds portion of a time value
Sgn Returns an integer that indicates a number’s sign
Shell Runs an executable program
Sin Returns a number’s sine
Space Returns a string with a specified number of spaces
Sqr Returns a number’s square root
Str Returns a string representation of a number
StrComp Returns a value indicating the result of a string comparison
String Returns a repeating character or string
Tan Returns a number’s tangent
Table 9-2 (continued)
Function What It Does
Time Returns the current system time
Timer Returns the number of seconds since midnight
TimeSerial Returns the time for a specified hour, minute, and second
TimeValue Converts a string to a time serial number
Trim Returns a string without leading or trailing spaces
TypeName Returns a string that describes a variable’s data type
UBound Returns the largest available subscript for an array’s dimension
UCase Converts a string to uppercase
Val Returns the numbers contained in a string
VarType Returns a value indicating a variable’s subtype
Weekday Returns a number representing a day of the week
Year Returns the year from a date value

Using Worksheet Functions in VBA

Although VBA offers a decent assortment of built-in functions, you might not always find exactly what you need. Fortunately, you can also use most of Excel’s worksheet functions in your VBA procedures. The only worksheet functions that you cannot use are those that have an equivalent VBA function.
VBA makes Excel’s worksheet functions available through the Worksheet Function object, which is contained in the Application object. (Remember, the Application object is Excel.) Therefore, any statement that uses a worksheet function must use the Application. Worksheet Function qualifier. In other words, you must precede the function name with Application.Worksheet Function (with a dot separating the two). The following is an example:
tmpD-82_thumb
You can omit the Application part of the expression because it’s assumed. You can also omit the Worksheet Function part of the expression; VBA will determine that you want to use an Excel worksheet function. But if you do so, then you must include the Application part. In other words, these three expressions all work exactly the same:
tmpD-83_thumb
My personal preference is to use the Worksheet Function part just to make it perfectly clear that the code is using an Excel function.

Worksheet function examples

In this section, I demonstrate how to use worksheet functions in your VBA expressions.

Finding the maximum value in a range

Here’s an example showing how to use the MAX worksheet function in a VBA procedure. This procedure displays the maximum value in the range named Number List on the active worksheet:
tmpD-84_thumb
You can use the MIN function to get the smallest value in a range. And, as you might expect, you can use other worksheet functions in a similar manner. For example, you can use the LARGE function to determine the kth-largest value in a range. The following expression demonstrates this:
tmpD-85_thumb
Notice that the LARGE function uses two arguments; the second argument represents the kth part — 2 in this case (the second-largest value).

Calculating a mortgage payment

The next example uses the PMT worksheet function to calculate a mortgage payment. I use three variables to store the data that’s passed to the Pmt function as arguments. A message box displays the calculated payment.
tmpD-86_thumb

As the following statement shows, you can also insert the values directly as the function arguments:

tmpD-87_thumb
However, using variables to store the parameters makes the code easier to read and modify, if necessary.

Using a lookup function

The following example uses the simple lookup table shown in Figure 9-1. Range A1:B13 is named Price List.
tmpD-88_thumb
You can download this workbook from the topic’s Web site.
The range, named Price List, contains prices for parts.
Figure 9-1:
The range, named Price List, contains prices for parts.

The procedure starts this way:

1. VBA’s InputBox function asks the user for a part number.
Figure 9-2 shows the Microsoft Excel dialog box that displays when this statement is executed.
2. This statement assigns the part number the user enters for the PartNum variable.
3. The next statement activates the Prices worksheet, just in case it’s not already the active sheet.
Use the InputBox function to get the user's input.
Figure 9-2:
Use the InputBox function to get the user’s input.
4. The code uses the VLOOKUP function to find the part number in the table.
Notice that the arguments you use in this statement are the same as those you would use with the function in a worksheet formula. This statement assigns the result of the function to the Price variable.
5. The code displays the price for the part via the MsgBox function.
This procedure doesn’t have any error handling, and it fails miserably if you enter a nonexistent part number. (Try it.) Add some error-handling statements for a more robust procedure. I discuss error handling in Chapter 12.

Entering worksheet functions

You can’t use the Excel Paste Function dialog box to insert a worksheet function into a VBA module. Instead, enter such functions the old-fashioned way: by hand. However, you can use the Paste Function dialog box to identify the function you want to use and find out about its arguments.
1. Activate a worksheet.
2. Choose Insert Function as you normally would.
3. Figure out how the function works.
4. Type the function and its arguments into your module.
Follow these steps to display the VBE’s Auto List Members option, which displays a drop-down list of all worksheet functions:
1. Type Application.Worksheet Function, followed by a period.
2. If this feature isn’t working, choose the VBE’s Tools Options command.
3. Click the Editor tab.
4. Place a check mark next to Auto List Members.

More about Using Worksheet Functions

Newcomers to VBA often confuse VBA’s built-in functions and Excel’s workbook functions. A good rule to remember is that VBA doesn’t try to reinvent the wheel. For the most part, VBA doesn’t duplicate Excel worksheet functions.
Bottom line? If you need to use a function, first determine whether VBA has something that meets your needs. If not, check out the worksheet functions. If all else fails, you may be able to write a custom function by using VBA.
The Worksheet Function object contains the worksheet functions available to VBA procedures. To see a list of these functions, you can use the Object Browser as shown in Figure 9-3. Follow these steps to display a complete list of worksheet functions available in VBA:
1. In the VBE, press F2.
The Object Browser appears.
2. In the Project/Library drop-down list (the one in the upper-left corner of the Object Browser), select Excel.
3. In the list labeled Classes, select Worksheet Function.
The Members of list shows all the worksheet functions you can use in your code.
For most worksheet functions that are unavailable as methods of the Application object, you can use an equivalent VBA built-in operator or function. For example, the MOD worksheet function is unavailable in
the Worksheet Function object because VBA has an equivalent, built-in Mod operator. This is by design — a VBA operator works faster than an Excel function in a VBA module.
Use the Object Browser to show the worksheet function available in VBA.
Figure 9-3:
Use the Object Browser to show the worksheet function available in VBA.

Using Custom Functions

I’ve covered VBA functions and Excel worksheet functions. The third category of functions you can use in your VBA procedures is custom functions. A custom function is one you develop yourself using (what else?) VBA. To use a custom function, you must define it in the workbook in which you use it.

Here’s an example of defining a simple Function procedure and then using it in a VBA Sub procedure:

tmpD-92_thumb
The custom function Multiply Two has two arguments. The Show Result Sub procedure uses this Function procedure by passing two arguments to it (in parentheses). The Show Result procedure then displays a message box showing the value returned by the Multiply Two function.
The Multiply Two function is fairly useless. It’s much more efficient to perform the multiplication in the Show Result Sub procedure. I include it simply to give you an idea of how a Sub procedure can make use of a custom function.
You can use custom functions also in your worksheet formulas. For example, if Multiply Two is defined in your workbook, you can write a formula such as this one:
tmpD-93_thumb
This formula returns the product of the values in cells A1 and A2.
Custom worksheet functions is an important (and very useful) topic. So important (and useful) that I devote an entire chapter to it. See Chapter 21.

Like this post? Please share to your friends:
  • Using formula in word
  • Using form fields in word
  • Using form controls in word
  • Using first letters to make a word
  • Using first letter from each word