Open In App

How to Get a List of User Defined Functions in Excel VBA?

Last Updated: 22 Feb, 2023

S

Summarize
Comments
Improve
Suggest changes
Like Article
Like
Share
Report
News Follow

Microsoft provides many built-in functions to speed up your work in Excel. However, you can technically create functions using VBA coding called “user-defined functions” (UDFs). Also known as a “user-defined function” in Excel VBA.

A formula that can be accessed from a worksheet using a piece of code is called a UDF. Simply put, formulas that are not built-in but available in Excel are called “user-defined functions”.

Using VBA, you can create user-defined functions (also called user-defined functions) that can be used in worksheets like regular functions. These are useful when existing Excel functionality is not sufficient. In such cases, you can create your own custom user-defined functions (UDFs) to meet your specific needs. This tutorial covers all about creating and using user-defined functions in VBA.

How to create User defined functions?

UDF is part of a module, but not part of a regular subroutine in VBA. In VBA they are called function procedures. Just like you start your macro coding with the word SUB, you should start it with the word “Function”. A sub-procedure has a beginning and an end. Similarly, a Function procedure has a Start and an End.

  • Create SUM function in Excel By adding two numbers. To start coding, start with the word “function” in one of your modules. Similar to how macros are named, functions must be named.
  •  We used this name as the expression name. Unlike subroutines, you cannot simply press “Enter” to create a procedure. But I have to mention the arguments here. 
  • For example, consider the following worksheet function SUM syntax: Unlike subroutines, you cannot simply press “Enter” to create a procedure. But I have to mention the arguments here.
    For example, consider the following worksheet function SUM syntax:
Defining SUM Function

 

Here we declare the arguments “x as integer” and “y as integer”. Since we are adding numbers, we only need to assign the data type as a numeric data type.

After declaring the arguments, we also assigned the return type to integer because the result returned by the OurSum function is also numeric.

Now, inside the function, we need to mention the formulas that we use. Here you have to use the function first.

Using SUM function

 

Another Example of a User-defined Function

Create a simple custom function in VBA and see how it works.

The following code creates a function that extracts the numeric part from an alphanumeric string.

Defining GetNumeric Function

 

If you have the above code in your module, you can use this function in your workbook.
Below is how this function GetNumeric is used in Excel.

Using GetNumeric Function

 

Before I show you how to create this function in VBA and how it works, there are a few things you should know.

Once a function is created in VBA, it can be used throughout the workbook like any other normal function. Typing an equal sign after a function name displays the function name in the list of matching functions. After typing =Get in the example above, Excel displayed a list of custom functions. I think this is a great example of how VBA can be used to create useful functions in Excel. You could do the same thing using formulas (as shown in this tutorial), but that would be complicated and hard to understand. With this UDF, you only need to pass one argument and get the result.

Result of GetNumeric Function

 

Arguments in a User-defined Function in VBA

In the example above where we created a custom function (GetNumeric) that retrieves the numeric part from an alphanumeric string, the function is designed to accept a single argument. This section describes how to create functions that take no arguments or multiple arguments (both required and optional).

Create a function in VBA without arguments

There are several functions in Excel worksheets that do not take arguments (RAND, TODAY, NOW, etc.).
These functions do not depend on any input arguments. For example, the TODAY function returns the current date and the RAND function returns a random number between 0 and 1. A similar function can also be written in VBA.
Below is the code that gives the name of the file. No arguments are required because the result that should be returned does not depend on the arguments.

Function without Arguments

 

The code above returns the result of the function as a string data type (I expect the filename to be a string as a result).
This function assigns the value of ThisWorkbook.Name to the function that is returned when the function is used on a worksheet.
Returns the name with the file extension if the file is saved. Otherwise, just return the name.
However, there is a problem with the above.
It doesn’t update automatically when the file name is changed. Functions are typically updated whenever their input arguments change. However, since this function has no arguments, the function is not recalculated (even if I rename the workbook, close it, and reopen it).

If necessary, you can force a recalculation using the keyboard shortcut (Ctrl+Alt+F9).

You need to add a line of code to recalculate the formula every time the worksheet changes.

In the code below, the function is recalculated every time there is a change in the worksheet (just like other similar worksheet functions like the TODAY and RAND functions).

re-iterating Function

 

If you change the workbook name, this function will update every time the worksheet changes or when you reopen this workbook.

Create a function in VBA with one argument

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

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

The function created with the following code converts the referenced text to uppercase. Now Excel already has a function for this. This function is just to show how it works. If you need to do this, I recommend using the built-in UPPER function.

Function with Single Argument

 

This function uses the VBA UCase function to change the value of the CellRef variable. Then assign that value to the ConvertToUpperCase function.

Since this function takes one argument, we don’t need to use the Application.Volatile part here. The function will automatically update as soon as the arguments change. 

Create a function in VBA with multiple arguments

Similar to worksheet functions, you can create functions in VBA that take multiple arguments. The code below creates a function that extracts the text before the specified delimiter. It takes two arguments, a cell reference containing a text string and a delimiter.

Function with Multiple Argument

 

If your user-defined function requires multiple arguments, each argument can be enclosed in parentheses and separated by commas.

Note that you can specify the data type for each argument. In the above example, CellRef was declared as Range data type and Delim was declared as String data type. If you don’t specify a data type, VBA assumes it’s a Variant data type.

When using the above function on a worksheet, the first argument must be the cell reference containing the text and the second argument must be the delimiter enclosed in double quotes.

The INSTR function of VBA is then used to check the delimiter’s position. The characters before the delimiter are then extracted using this position (using the LEFT function).

The function is then given the result as a final step.

This equation is far from ideal. For instance, it would give you an error if you entered a delimiter that wasn’t present in the text. Now you can either use the worksheet’s IFERROR function to remove the errors or the code below, which returns the complete text if it can’t locate the delimiter.

Function with Delimiter locator

 

We can improve this function even further.

It would give you an error if you directly entered the text (from which you wish to extract the portion before the delimiter) into the function. Please give it a try!

Because we designated the “CellRef” as a range data type, this occurs.

The method above also prevents you from using the cell reference rather than hard coding the delimiter’s location in the formula if you want the delimiter to be in a certain cell. The Delim has been specified as a string datatype, which is why.

Remove the data type declaration if you want the function to be flexible enough to take user-supplied cell references or direct text input.

As a result, the argument would become a variant data type that can handle any kind of argument.

argument would become a variant data type

 

Create a function in VBA with an optional argument

In numerous Excel functions, some of the arguments are optional. The venerable VLOOKUP function, for instance, has 3 required arguments and 1 optional one.

As the name implies, it is not required to specify an optional parameter. If you omit one of the required arguments, your function will give you an error; but, if you omit the optional argument, your function will still function.

Optional arguments, however, are not pointless. They give you a variety of options to pick from.

For instance, the VLOOKUP function does an approximate lookup if the fourth argument is omitted, and an exact match if the last argument is specified as FALSE (or 0).

Keep in mind that all optional arguments must come after any necessary arguments. Optional parameters cannot be used at the beginning. Now, let’s look at how to add optional parameters to a VBA function.

Function with only an optional argument

I may be mistaken, but to my knowledge, there isn’t an intrinsic function that only accepts optional inputs. However, we can make one using VBA.

The function’s code is shown below. It returns the current date in two formats: dd-mm-yyyy if no argument is provided (i.e., leave it empty) and dd mmmm, yyyy if an argument is provided (i.e., anything so that the argument is not blank).

Function with only an optional argument

 

Note that the aforementioned function checks to see if the argument is missing or not using the ‘IsMissing’ function. Your optional argument must be of the variant data type in order to use the IsMissing method.

No matter what you enter as the argument, the aforementioned function operates. Only the optional argument’s presence or absence is checked in the code.

By limiting accepting certain values as parameters and displaying an error in the remaining circumstances, you can increase this’s robustness (as shown in the below code).

 

The code above generates a function that displays the date in two formats: “dd-mm-yyyy” if an argument is not provided and “dd mmmm,yyyy” if the input is. In every other situation, it returns an error.



S

News
Improve
Discuss
Do you want to advertise with us?Click here to know more

How to Debug a User Defined Function in Excel VBA

article_img
Debugging a User Defined Function (UDF) in Excel VBA can feel like a detective mission where you search for clues to fix issues in your code. When a custom function doesn’t deliver the expected results, it can disrupt your workflow and lead to frustration. Fortunately, debugging tools in VBA make it possible to identify exactly what's going wrong and why. In this article you will learn the effective techniques to debug your UDFs, helping you find errors, understand how your code runs, and ensure your functions work seamlessly. Whether you're a beginner or an experienced user, mastering these debugging skills can save you time and turn coding headaches into problem-solving victories.Table of ContentWhat is a User Defined Function in Excel What is Debugging in Excel VBA How to Create a User-Defined Function in Excel VBAHow to Debug a User-Defined Function in Excel VBACommon Debugging Tools in Excel VBAUDF works in debug mode but it doesn't give value into the cell: 9 Best ways to ResolveHow to Debug a Custom Function in ExcelWhat is a User Defined Function in Excel A User Defined Function (UDF) in Excel VBA is a custom function created by users to perform specific tasks or calculatio
Read More

How to Create a User Defined Function in Excel VBA

article_img
A function is a collection of code.  As a developer, we very often need a custom function (User-defined function) in our projects. These functions can be used as normal functions in Excel. These are helpful when the existing functions are not enough. In such cases, the user can create his own custom user-defined function to fulfil the need.  What are User Defined FunctionsUser Defined Function(UDF) is the custom function that is created by the user to perform a specific task in VBA(Virtual basic application) which is a programming language in Excel. Function Vs. Subroutine in VBA In VBA, a 'Subroutine' lets you run a group of commands, while a 'Function' provides a result. For example, consider a list of numbers, some positive and some negative. With a subroutine, you can scan each cell and mark negative ones by changing their colour. The subroutine modifies the cell properties. On the other hand, a custom function can be used in a separate column. It returns TRUE for negative values and FALSE for positive ones. Functions can't change cell properties directly but can be used with conditional formatting for the same effect. When you create a User Defined Function (UDF) in VBA, you c
Read More

VBA Subroutine in Excel - How to Call Sub in VBA?

article_img
When a specified action is performed on a worksheet with the help of a collection of code known as a VBA Subroutine. It also helps to read an external file, also it can open other applications from Excel. A large piece of code can be broken into small parts so that we can manage it easily. Let's learn why to use submarines: Converts large piece of codes into small parts so that the computer ignores all kind of complexities that arises because of large codesReusability of code suppose we in a program have to access the database frequently so instead of writing the code again and again we can create a function to access the databaseSubroutines are self-documenting functions which means a coder can easily say what the program does by looking into the name of the function Naming Rules of SubroutinesIt can start with a letter or an underscore but it cannot start with a number or a special character.It cannot contain any space in the name.The name of the subroutine cannot be a keyword like Private, Sub, End, etc. Syntax Private Sub function_name( ByVal arg1 As String, ByVal arg2 As String) End Sub Syntax Explanation Code Action "Private Sub function_name(...)"Private is the keyword whic
Read More

VBA Date and Time Functions in Excel

article_img
Date and Time Functions are the inbuilt functions that give us the opportunity to see the date or time according to the user's need. Suppose a user needs to see the month or the day or the year then it can be easily seen by different date functions. Similarly, for the time function, also we can manipulate it according to the need of the user. Date and Time functions are used to interconvert date and time in different formats. In this article, we will learn about the most commonly used date and time functions. VBA Date Functions There are fifteen-plus different date functions in VBA, but here we will talk about some of the most commonly used date functions. VBA Date Function The Date() function returns the current date. The Date() function does not require any arguments. For example, declare a variable name date_1 of Date data type, call the Date() function, and store the return value in date_1, then print the date_1 in the console. Syntax of the function: Date() VBA DateAdd Function The DateAdd() function is used to add an interval of date/time to the respective date or time. The function will return the resulting date or time. The function takes three arguments, Interval, Nu
Read More

Excel VBA | sum() functions

article_img
Visual Basic for Applications (VBA) is the programming language of Excel and other offices. It is an event-driven programming language from Microsoft. With Excel VBA one can automate many tasks in excel and all other office software. It helps in generating reports, preparing various charts, graphs and moreover, it performs calculation using its various functions. Let's see Sum functions in Excel. SUM: Adds all the numbers in a range of cells. Syntax: =SUM(number1, number2…) Here, number 1: This is the first number in your cell to add. You can specify it upto 255 numbers. number 2: This is an Optional field. You can add upto 255 numbers. Example: Output: SUMIF: Allows to add the cells depending upon the criteria you’ve provided. Syntax: =SUMIF(range, criteria, sum_range) range: It is the range of cells which you want to evaluate. The cells in range can be numbers, names or arrays or any other reference that contains numbers. criteria: It should be in the form of a number or any expression which defines which all cells to be added. For instance, “mango”, C6, “<35” sum_range: This field is Optional. If this is not mentioned, Excel will add only those cells on which criteria is appl
Read More

Excel VBA | Average() Functions

article_img
VBA (Visual Basic for Applications) is the programming language of Excel and other offices. It is an event-driven programming language from Microsoft. With Excel VBA, one can automate many tasks in excel and all other office softwares. It helps in generating reports, preparing various charts, graphs and moreover, it performs calculation using its various functions. Let's see Average functions in Excel. AVERAGE It returns the arithmetic mean of all of its arguments. Syntax: =AVERAGE(number1, number2, …) Here, number 1: This is the first number in your cell. You can specify it upto 255 numbers. number 2: This is an Optional field. You can specify it upto 255 numbers. Example: Output: AVERAGEIF: It calculates the average of only those values which meet a certain criteria. Syntax: =AVERAGEIF(range, criteria, average_range) range: It is the range of cells to be evaluated. The cells in range can be numbers, names, arrays or any other reference that contains numbers. Blank and text values are not considered. criteria: It should be in the form of a number or any expression which defines which all cells to be averaged. For instance, “mango”, C6, “<35” average_range: [Optional] If this
Read More

Excel VBA | count() functions

article_img
Visual Basic for Applications (VBA) is the programming language of Excel and other offices. It is an event-driven programming language from Microsoft. With Excel VBA one can automate many tasks in excel and all other office software. It helps in generating reports, preparing various charts, graphs and moreover, it performs calculation using its various functions. Let’s see Count() functions in Excel. COUNT: It allows to count the number of cells that contain numbers in a range. One can use the COUNT function to calculate the total number of entries in an array of numbers. Syntax:=COUNT(value1, value2…) value1: The very first item required to count numbers. value2: It can be specified upto 255 other entries which you want to count. Note: -> Only those arguments are counted that are numbers or text enclosed between quotation marks, as, “2”. -> Arguments like logical values and text representation of numbers that are typed directly are counted. -> Any values that cannot be translated to numbers are ignored. Example: Output: COUNTA: This counts only those range of cells which are not empty. Syntax:=COUNTA(value1, value2…) value1: It is the first argument to be counted. value2: All addi
Read More

How to Get Length of Array in Excel VBA?

article_img
We use UBound and LBound functions to get the length of an Array in Excel VBA. In this article, we will discuss them in detail. Syntax: UBound() function UBound (arrayname, [ dimension ]) Parameters: arrayname: required. Array variable namedimension: optional Returns: Return upper limit of an array dimension. Syntax: LBound() Function LBound (arrayname, [ dimension ]) Parameters: arrayname : required. Array variable namedimension : optional Returns: Return lower limit of an array dimension Sample Data: VBA Code to get the length of Array (one-dimensional array): Declare Variables: Declaring a customer array with the size of 10. Sub oneDimArrayLength() ' Array variable Declaration Dim customer (1 To 10) As String Assign values to array elements customer(1) = "ANTON" customer(2) = "BERGS" customer(3) = "BOLID" customer(4) = "KOENE" customer(5) = "FRANS" Use UBound function to get the size of an array and Message box to display the result 'Message box to popup length of 1D array MsgBox "Array has " & UBound(customer) & " element(s)." End Sub To Run VBA Code Press Alt+F8 to popup macro window. Select " oneDimArrayLength" and Click Run button. Output VBA Code to get the length
Read More

Get, Set, or Change Cell value in Excel VBA

article_img
VBA, or Visual Basic for Applications, is a programming language developed by Microsoft. It is used to automate repetitive tasks, enhance functionality, and create custom solutions within Microsoft Office applications like Excel, Word, and Access. VBA allows users to write scripts or small programs to perform tasks such as data manipulation, complex calculations, and generating reports, making work more efficient and customized to specific needs. We use VBA to automate our tasks in Excel. The idea of using VBA is to connect the interface of Excel with the programming. One of the very most important connections between them is by changing the cell values. The change in cell value by programming shows the power of VBA. In this article, we will see how to set, get, and change the cell value.  Get, Set, or Change Cell value in Excel VBAHow to Set Cell Value in Excel VBAAssigning a cell with a value can be achieved by very two famous functions in VBA i.e. Range and Cells function.  Range Function in VBAThe range function helps access the cells in the worksheet. To set the cell value using the range function, we use the .Value.  Syntax: Range(cell_name).Value = value_to_be_assinged. 1. S
Read More

How to Use Select Case Statement in Excel VBA?

article_img
VBA in Excel stands for Visual Basic for Applications which is Microsoft's programming language. To optimize the performance and reduce the time in Excel we need Macros and VBA is the tool used in the backend. In this article, we are going to discuss how to use Select Case Statement in Excel VBA. Select Case Statement of Excel VBA The select case in VBA is like a detective that investigates an expression by checking it against different scenarios listed as Case Statements, each with its own conditions. When a scenario matches the expression, it's like solving a piece of the puzzle, and the corresponding code linked to that scenario is activated. Importantly, once a match is found, the detective stops investigating and moves on to executing the discovered code. Yet, if none of the scenarios match, it's like the detective hitting a dead end. In this situation, the code associated with the Case Else statement comes into play, offering a default solution or outcome. Syntax of the Select Case Statement of Excel VBAThe VBA Select Case Statement shares similarities with the Switch Case construct found in programming languages such as Java, C#, and PHP. In Excel VBA, this statement helps
Read More
three90RightbarBannerImg