Open In App

How to Create a User Defined Function in Excel VBA

Last Updated: 17 May, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Share
Report
News Follow

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 Functions

User 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 can use it just like any other Excel function, as I’ll explain further in the ‘Different Ways to Use a User Defined Function in Excel’ section.

Function Definition

VBA, a function is like a helpful tool that can give you a result if you ask it nicely. It’s like having a magic box that you put some things into (we call them parameters), and it gives you something back (we call it a return value).

One cool thing about this magic box is that it can give you not just one thing but a bunch of things all at once, and we call that a list or an array.

Before you can use this magic box, you need to tell VBA how it works. You do this by using the word “Function,” giving your magic box a special name, and then describing how it should work with any parameters it needs. Finally, you use “End Function” to say you’re done explaining.

Syntax

Function Functionname(parameter-list)

statement 1

statement 2

statement 3

…….

statement n

End Function

How to Create a User-Defined Function in VBA

 Here we explain how to create a UDF (user-defined function) to count/return the Number of vowels in a given string using Excel VBA.  

Example Custom Function Syntax

Function Name: countvowel()

Input parameter: an excel cell

Output: Return an interger (Number of vowels)

Implementation

Follow the below steps to create a User-defined Function in Excel VBA:

Step 1: Open an excel file, To create user-defined function “countVowel()” function.

Step 2: Press Alt + F11 – to open Visual Basic Editor.

Open Excel VBA window.

Step 3: Click Insert >> Module – which will add a new module as in Img1.

Click on Insert then press Module.

The VBA code window will be opened where you can write the code of the Function.

Write your code here.

Img 1

Step 4: Type the below code in “code window”.

  • Function name with parameter Range

Function countVowel(rg As Range)

  • Iterate each character of a given string and check the character is vowel or not.  If it is vowel character increase vowelCount = vowelCount +1

For i = 1 to Len(rg.Value

textValue = UCase(Mid(rg.value, i, 1))

If textValue Like “[AEIOU]”  then

vowelCount = vowelCount +1 

End If

Next i

  • Returns Number of vowels.

countvowel = vowelCount

End Function

Code of VowelCount.

Step 5: Save your Excel workbook as Excel Macro-Enabled Workbook (*.xlsm) 

Save your workbook.

Calling a Function

To activate a function, you simply use the function name, just like in the example provided in the screenshot.

Step 1: Type “Customer” in cell “A1” and “Vowels_Count” in cell “B1” as header.

  • Fill names in cells A2:A6

Fill the details.

Step 2: Write below formula in cell “B2” and drag it to fill “B2:B6” .

=countVowel (A2)

Apply the formula

Step 3: Preveiw the Result

Count_of_vowel is used.

Scope of User Defined Function

Public 

You have to make your function public if you want to access that function in all worksheets of the workbook. For making a function public, you just need to use the word “Public”. 

Public Function countVowel(rg As Range)

(WHOLE CODE)

Note: By default the functions are public. if you don’t make it private.

Private

When you make a function private you can use that particular function in the procedure of the same module. To make a function private just use the word “Private”

Private Function countVowel(rg As Range)

(WHOLE CODE)

If you have made a function privately in Module 1, then you can it in procedures you have in Module 1. And it won’t appear in the function list of teh worksheet (when you use = sign and try to type the name) but you can use it by specifying it’s name and arguments.

Also Read

Function and Sub in Excel VBA

FAQs on Excel VBA

Why you should create a User defined function?

Following can be the reasons to create user defined function

When there is no function for this

Sometimes there is no specific formula for what you need to calculate. In that case you can create your own function to perform a particular task.

Replace a complex Formula

There are some formulas which are difficult to understand and also hard to use. In that case you can create your own easy custom formula to perform a particular task. 

When you don’t want to use Sub Routine

Although you can use a VBA code to perform a calculation but if you want to repeat the task then you have to run that code and again if you update your calculation. But if you convert that code into a function then you simply insert it as a function instead of running that code again and again.

How you can create a user defined function in Excel?

Creating a custom function in Excel is a process that can be divided in following ways:

1. At the very first you have to declare your Procedure as a Function

2. Defining its Argument and their Data Type

3. Add code to calculate the desired value.

functions

What are the different ways to create a VBA function in Excel?

Without any Argument

With just one Argument

With Multiple Argument

Using Array as the Argument

What are the Limitations of using User Defined Function in Excel?

Following are the limitation of User Defined Function in Excel:

  • It can’t make changes to any of the environment options
  • Make changes to another cell’s value.
  • You can’t change, delete or format cells and a range by using a custom function.
  • It does not allow to rename, or add worksheets to a workbook.


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 Get a List of User Defined Functions in Excel VBA?

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

How to Create Dynamic Range Based on Cell Value in Excel VBA?

article_img
Dynamic ranges in excel VBA provide us with the flexibility to define ranges beyond the specific values. The dynamic range enables the program to perform transformation and data management steps with ease without the worry of changing the range of the data set. The dynamic range in excel VBA promotes code reusability and does not make the programming logic to be redundant. By utilizing the range object and cells object, the dynamic ranges in Excel VBA can be defined and created. There are many ways in which dynamic ranges can be created. Following are the methods listed below: Variable initialization to the range and cell object.Create a Dynamic range passed as the value in another excel cell. The following examples help in illustrating the above methods, Variable Initialization to Range and Cell Object With the change in the size of the data, it would be useful if the range object that is used to refer to the ranges can be modified. The following code helps in counting the last row and column in an excel as shown below Sub test() Dim EndR As Integer Dim lastCl1 As Integer Sheet2.Activate EndR = Sheet2.Range("A1").End(xlUp).Row lastCl1 = Sheet2.Range("XFD1").End(xlToLeft).Column Ms
Read More

How to Create Charts in Excel Using Worksheet Data and VBA?

article_img
Excel is an important software provided by Microsoft Corporation. This software belongs to one of the major software suites Office 365. In this software suite, there are other software are present like Word, PowerPoint, etc. They are called Office 365, as this software are mostly used for office purpose. But now the world has changed a lot. After the Corona Pandemic, the world knows the positivity of using digital tools. Office 365 was not different from that. As a part of the software suite, Excel software also gains some importance from the users. They are not only used for official purposes. But they can also be used for school purposes. Excel is software that can able to store data in an effective form. So, searching for the data becomes more manageable in this software. Excel has another great feature. It can be used to derive the charts from the provided data. The charts are helpful for analyzing any growth of the data. If there are thousands of data present, it is a difficult task to extract some analysis from that data. But if those data are converted to charts, then it will be easy to analyze those data. Excel sheet helps to do the same. Charts can be prepared whatever the
Read More

How to Create an Input Box With Multiple Inputs in Excel Using VBA?

article_img
The Input Box is a dialogue box that helps users to take a value and do later computations according to the entered value. The input box is similar to the message box, but the message box is used to display the data while the input box is used to enter the data. By default, a message box displays only the Ok button in its conversation box, whereas an input box displays both the Ok and Cancel buttons. You can specify the type of data to be returned. In excel VBA Macro, Input Box is one of the most commonly used functions. In this example, we will learn how to create an input box using excel VBA which consumes multiple data from the end-user. For this, we will be creating a user form. Step By Step Implementation Step 1: Insert Visual Basic Editor To insert Visual Basic Editor in excel please refer to How to Insert and Run VBA Code in Excel? Step 2: Insert User Form In this step, we need to add a user form to our VBA. For this, we need to go to the Developer tab on the top of the ribbon and then select Visual Basic. Fig 1 - Open Visual Basic Once we click on the Visual Basic option, excel will open Visual Basic Editor in a new window. Fig 2 - Visual Basic Editor In the Visual Basic Ed
Read More

Function and Sub in Excel VBA

article_img
In Visual Basic, the functions and sub-procedures play similar roles but have different or unique characteristics. However, both perform a programmed task. They utilize a set or group of commands to deliver the required results. The key difference between the sub and the functions is that a sub-procedure generally does not return a result whereas functions tend to return a result. Hence if there is a need for having a value post execution of tasks, then place the VBA code under a function or otherwise place the code under a sub-procedure. In Excel, there is the availability of large numbers of VBA functions that could be utilized in the development of new VBA codes. Such functions are referred to as Built-in functions. With the increase in the size of a VBA program, both Functions and Sub-procedures play a crucial role in the management and performance of VBA code. Functions in VBA A function in VBA can be defined as a procedure that executes a piece of code or instructions and post-execution, it returns the value of the tasks performed. A function is hence invoked using a variable. Functions are directly called in the spreadsheets by using excel based formulas. An excel VBA functi
Read More

InputBox Function in Excel VBA

article_img
Input Box is one of the most frequently used functions in VBA Macro. The dialogue box that appears asks for input from the user and returns a constant/code/number/text. For example, if you want to create a log-in form in VBA, you will require an input box function. Let's learn how to create an input box in VBA. InputBox FunctionInput Box is a dialogue box that helps users to take value, and do later computations according to the entered value. The input box is similar to the message box, but the message box is used to display the data while the input box is used to enter the data. By default, a message box shows only the OK button in its dialogue box but the input box shows both the OK and Cancel buttons in its dialogue box. You can choose the return type of the data to be entered. The automated data analysis includes entering and displaying the data, which can be achieved if we are using the input box and message box simultaneously. Syntax: InputBox(prompt[,title][,default][,xpos][,ypos][,helpfile, context]) Temporary and Permanent Arguments in Input BoxArguments of the Input box, help customize your input box by changing the title, fixing the position, adding help buttons, etc
Read More

VBA Find Function in Excel

article_img
In an Excel sheet subset of cells represents the VBA Range which can be single cells or multiple cells. The find function will help to modify our search within its Range object. A specific value in the given range of cells is to search with the help of the Find function. Excel VBA provides different parameters in the Find function so that we can search according to the search order or direction and also we can make a case-sensitive search which will be discussed further in this article. Excel VBA Find FunctionAs we know about the Find Function in Excel, we can use the Shortcut key "Ctrl+F" to find the content that you are looking for. The FIND function of VBA searches for a specified value in the range that is defined by the user. A VBA code is written by entering arguments of the FIND function. Below is the syntax given for using the find function in VBA, Syntax: Find(What, [After], [LookIn], [LookAt], [SearchOrder], [SearchDirection AsXlSearchDirection = xlNext], [MatchCase], [MatchByte], [SearchFormat]) As Range Parameter Required Description WhatRequiredThe value for which we are searchingAfterOptionalRange of cells from where the search will startLookinOptionalFunction search
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