Press Alt + F11, choose Insert → Module and write a Function that assigns its result to its own name:
Function DayName(d As Date) As String
DayName = Format(d, "dddd")
End Function
Use it in the sheet like any built-in function, for example =DayName(A2). It also appears under User Defined in Insert Function.
Put UDFs in a standard module, not a sheet or ThisWorkbook module, or Excel returns #NAME?. The same error appears when macros are disabled, or when the function name looks like a cell reference, such as TAX1.
A UDF can only return a value. It can’t change other cells, formats or sheets; code that tries is ignored or makes the cell show #VALUE!. Use a Sub for actions. Make an argument optional with a default, as in Function RemoveFirst(txt As String, Optional n As Long = 1) As String.
Save the file as .xlsm. To use the function in every workbook, save it as an add-in (.xlam) and switch it on under File → Options → Add-ins. A function kept in PERSONAL.XLSB has to be called as =PERSONAL.XLSB!DayName(A2).
Probably one of the coolest benefits of learning VBA is the ability to create your own functions.
In Excel, there are more than 500 functions, and some of them are highly useful in your daily work. But Excel gives you the ability to create a custom function using VBA. Yes, you got it right. USER DEFINED Function, in short UDF, or you can also call it a Custom VBA function.
And there’s one thing that I can say with confidence: every aspiring VBA user wants to learn to create a User Defined Function. Don’t you? Say “Yes” in the comment section, if you are one of those people who want to create a custom function.
I’m excited to tell you that this is a COMPLETE GUIDE to help you to create your first custom function using VBA and apart from this I have shared some examples of USER-DEFINED Functions to help you to get inspired.
- Here I’ll be using the words User Defined Function, custom function, and UDF interchangeably. So stay with me; you are going to be a VBA rock star in the next couple of minutes.
- To create a code for the VBA custom function, you need to write it; you can’t record it using the macro recorder.
Why You Should Create a Custom Excel Function
As I said, there are a lot of in-built functions in Excel which can help you to solve almost all the problems and do all kinds of calculations. But, sometimes, in specific situations, you need to create a UDF.
And, below I have listed some of the reasons or situations in which you need to go with a custom function.
1. When there is no Function for this
This is one of the common reasons for creating a UDF with VBA, because sometimes you need to calculate something, and there is no specific function for it. I can give you an example of counting words from a cell and for this, I found a UDF can be a perfect solution.

2. Replace a Complex Formula
If you work with formulas, I’m sure you know that complex formulas are hard to read and sometimes even harder for others to understand. So a custom function can be a solution to this problem because once you create a UDF you don’t need to write that complex formula again and again.

3. When you don’t want to use SUB Routine
You can use a VBA code to perform a calculation, but VBA codes are not dynamic. You need to run that code again if you want to update your calculation. But if you convert that code into a function then you don’t need to run that code again and again as you can simply insert it as a function.
How to Create Your First User Defined Function in Excel
OK so look. I have split the entire process into three steps:
- Declaring your Procedure as a Function
- Defining its Arguments and their Data Type
- Add code to Calculate the Desired Value
But let me give you an example first:
You need to create a function that can return the name of the day from a date value. Well, we have a function that returns the day number of the week but not the name. You got what I’m saying? Yes?
So, let’s follow the below steps to create your first user-defined function:
- First of all, open your visual basic editor by using the shortcut key ALT + F11 or go to Developer Tab and simply click on the “Visual Basic” button.

- The next thing is to insert a module, so right-click on the VBA project window and then go to insert, and after that click “Module”. (ALERT: You need to enter a USER DEFINED FUNCTION only into standard modules. Sheet and ThisWorkbook modules both are a special type of module and if you enter a UDF in these two modules, Excel does not recognize that you are creating a UDF).

- The third thing is to define a name for the function and here I’m using “myDayName”. So you must write “Function mydayName”. Why Function before the Name? As you are creating a VBA function so the using the word “Function” tells Excel to treat this code as a function (make sure to read the scope of a UDF ahead in the post).

- After that, you need to define arguments for your function. So insert starting parentheses and write “InputDate As Date”. Here InputDate is the Argument’s name and date is its data type. It’s always better to define a data type for the argument.

- Now, close the parentheses and write “As String”. Here you are defining the data type of the result returns by the function and as you want day name which is a text so its data type should be as “String”. If you want to have the result which is other than a string make sure to define its data type according to that. (Function myDayName(InputDate As Date) As String).

- In the end, hit ENTER. At this point, your function’s name, its argument, argument’s data type, and function’s data type is defined and you have something like below in your module:

- Now within the “Function” and “End Function”, you need to define the calculation or you can say working of this UDF. In Excel, there is a worksheet function called “Text” and we are using the same here. And for this, you need to write the below code and with this code, you are defining the value which should be returned by the function. myDayName = WorksheetFunction.Text(InputDate, “dddd”)

- Now, close your VB editor and go back to the worksheet and in the cell B2, enter “=myDayName(A2)” hit enter and you’ll have the day name.

Congratulations! You have just created your first User Defined Function. This is the moment of real Joy. Isn’t it? Type “Joy” in the comment section.
How this Function Works and Return Value in a Cell
Your first custom function is here, but the thing is, you need to understand how it works. If I say in simple words, it’s a VBA code but you have used it as a function procedure. Let’s divide it into three parts:
- You enter it in a Cell as Function and Specify the Input Value.
- Excel runs the code behind the function and uses the value which you have referred to.
- You got the result in the cell.
But you need to understand how this function works from inside. So I have split the entire process into three different parts where you can see how the code which you have written for the function actually works.

As you have specified “InputDate” as the argument for the function and when you enter the function in the cell and specify a date, VBA takes that date value and supply it to the text function which you have used in the code.
And in the example which I have mentioned above, the date you have in cell A2 is 01-Jan-2019.
After that, the TEXT function converts that date into a day name using the format code “dddd” (the code for the full day name), which you have already mentioned in the function code. And the day name returned by the TEXT function is assigned to “myDayName”.
So if the result of the TEXT function is Tuesday that value will be assigned to the “myDayName”.
And here the working of the function comes to an end. “myDayName” is the name of the function, so any value which is assigned to “myDayName” will be the result value and the function which you have inserted in the worksheet will return it in the cell.
When you write a code for a custom function, there’s one thing you need to take care of: the value that the code returns must be assigned to the function’s name.
How to Improve a UDF for Good
Well, you know how to create a custom VBA function.
Now…
There’s one thing you need to take care of: the code you have used in the function should be good enough to handle all the possibilities. The function which you just wrote above can return the day name from a date.
But…
What if the value you have specified is not a date? And what if the cell you have referred to is blank? There can be other possibilities but I’m sure you got my point.
Right? So, let’s try to improve this custom function so that it can deal with the above problems. Alright. First of all, you need to change the data type of the argument and use:
InputDate As Variant
With this, your custom function can take any kind of data type as input. Next, we need to use VBA IF statement to check InputDate for some conditions. The first condition is if the cell is blank or not. And for this, you need to use below code:
If InputDate = "" Then myDayName = ""
This will make the function return blank if the cell you have referred to is blank.
One problem is solved, let’s get into the next one. Other than a date there are possibilities that you can have a number or a text. So, for this, you also need to create a condition that should check whether the value referred is an actual date or not.
The code would be:
If IsDate(InputDate) = False Then myDayName = ""
Here I’m using a blank for both of the conditions so that if you have large data, you could easily filter values where the input value is not valid. So, after adding the above conditions, the code would look like:
Function myDayName(InputDate As Variant) As String If InputDate = "" Then myDayName = "" Else If IsDate(InputDate) = False Then myDayName = "" Else myDayName = WorksheetFunction.Text(InputDate, "dddd") End If End If End Function
And that’s how it works now. I’m sure you can still make some changes to this function, but I’m sure you got my point clearly.
How to use a Custom VBA Function
At this point, you’re pretty much clear about how you can create a VBA function in Excel. But once you have it, you need to know how you can use it. And in this part of the post, I’m going to share with you how and where you can use it. So, let’s jump into it.
1. Simply within a Worksheet
Why do we create a custom function? Simple. To use it in the worksheet. You can simply enter a UDF in a worksheet by typing the equal sign and the name of the function and then specifying its arguments.

You can also enter a user-defined function from the function library. Go to the Formulas Tab ➜ Insert Function ➜ select the “User Defined” category.

From this list, you can choose the UDF you want to insert.
2. Using other Sub Procedures and Functions
You can also use a function within other functions or in a “Sub” procedure. Below is a VBA code where you have used the function to get the day name for the current date.
Sub todayDay() MsgBox "Today is " & myDayName(Date) End Sub
Make sure to read “Scope of a UDF” ahead in this post to learn more about using a function in other procedures.
3. Accessing Functions from Other Workbook
If you have a UDF in one workbook and you want to use it in another workbook or in all the workbooks, you do it by making an add-in for it. Follow these simple steps:
- First of all, you need to save the file (in which you have the custom function code) as an add-in.
- For this, go to the File Tab ➜ Save As ➜ “Excel Add-in (*.xlam)”.

- After that, go to File ➜ Options ➜ Add-ins, select Excel Add-ins in the Manage box and click Go. Click Browse, select your add-in, make sure its check box is ticked and click OK.

That’s it. Now you can use all of your VBA functions in any workbook you open on this computer.
Different Ways to Create a Custom VBA Function [Advanced Level]
At this point, you know about creating a custom function in VBA. But the thing is when we use In-Built functions, they come with different types of arguments.
So in this section of this guide, you’re going to learn how to create a UDF with the different types of arguments.
- Without Any Arguments
- With Just One Argument
- With Multiple Arguments
- Using Array as the Argument
…let’s move ahead.
1. Without Any Arguments
Do you remember functions like NOW and TODAY, where you don’t need to enter any argument?
Yes. You can create a User Defined Function where you don’t need to enter an argument. Let’s do it with an example:
Let’s create a custom function that can return the location of the current file. And here’s the code:
Function myPath() As String Dim myLocation As String Dim myName As String myLocation = ActiveWorkbook.FullName myName = ActiveWorkbook.Name If myLocation = myName Then myPath = "File is not saved yet." Else myPath = myLocation End If End Function
This function returns the path of the location where the current file is stored, and if the workbook is not saved yet, it will show a message that says “File is not saved yet”.

Now, if you pay close attention to the code of this function, you don’t have to define any argument (within the bracket). You have just defined the data type for the function’s result.
The basic rule of creating a function without an argument is to write code where you don’t need to input anything.
In simple words, the value you want to have in return from the function should be calculated automatically.
And in this function, you have the same thing.
The code ActiveWorkbook.FullName returns the full path of the file, and ActiveWorkbook.Name returns the name. You don’t need to input anything.
2. With Just One Argument
We have already covered this thing while learning how to create a user-defined function. But let’s dig a bit deeper and create a different function. This is a function that I created a few months back to extract URL from a hyperlink.
Function giveMeURL(rng As Range) As String On Error Resume Next giveMeURL = rng.Hyperlinks(1).Address End Function
Now in this function, you have just one argument.

When you enter this in a cell and then specify the cell where you have a hyperlink, it will return the URL from the hyperlink. Now in this function, the main work is done by:
rng.Hyperlinks(1).Address
But the rng is what you need to specify. Say “Easy” in the comment section if you find creating a UDF easy.
3. With Multiple Arguments
Normally, most of the Excel’s In-Built Functions have multiple arguments. So it’s a must for you to learn how to create a custom function with multiple arguments.
Let’s take an example: You want to remove particular letters from a text string and want to have the rest of the part.
Well, you can do it with RIGHT and LEN in a worksheet formula, but here we will use the same two functions inside a custom VBA function, so you only need to enter the cell and the count.
So, here’s the function:
Function removeFirstC(rng As String, cnt As Long) As String removeFirstC = Right(rng, Len(rng) - cnt) End Function
OK so look:

In this function, you have two arguments:
- rng: In this argument, you need to specify the cell from where you want to remove the first character of a text.
- cnt: And in this argument, you need to specify the count of the characters to remove (If you want to remove more than one character from the text).
When you enter it in a cell, like =removeFirstC(A1,2), it removes the first two characters from the text in cell A1.
3.1 Creating a User Defined Function with Optional as well as Required Argument
If you think about the function we have just created in the above example where you have two different arguments, well, both of them are required. And, if you miss any of these you’ll get an error like this.
Now if you think logically, the function we have created is to remove the first character. But here you need to specify the count of the characters to remove. So my point is this argument should be optional and must take one as a default value.
What do you think?
Say “Yes” in the comment section if you agree with me on this.
OK so look. To make an argument optional you just need to add “Optional” before it. Just like this:
Function removeFirstC(rng As String, Optional cnt As Long = 1) As String
The “= 1” at the end of the optional argument is its default value, which VBA uses when you leave that argument out.
But the important thing is to make your code work with or without the value of that argument. So, our new code for the same function would be like this:
Function removeFirstC(rng As String, Optional cnt As Long = 1) As String
If cnt >= Len(rng) Then
removeFirstC = ""
Else
removeFirstC = Right(rng, Len(rng) - cnt)
End If
End Function
Now in the code, if you skip specifying the second argument, like =removeFirstC(A1), it removes just the first character. And if the count is more than the length of the text, it returns a blank instead of the #VALUE! error.
4. Using Array as the Argument
There are a few In-built functions that can take arguments as an array and you can also make your custom VBA function to do this.
Let’s do it with a simple example where you need to create a function that sums the values from a range where you have both numbers and text. Here we go.
Function addNumbers(CellRef As Range) Dim Cell As Range For Each Cell In CellRef If IsNumeric(Cell.Value) = True Then Result = Result + Cell.Value End If Next Cell addNumbers = Result End Function
In the above code of the function, we have used an entire range A1:A10 instead of a single value or a cell reference.

By using a FOR EACH loop, it will check every cell of the range and sum the value if the cell has a number in it.
The Scope of a User-Defined Function
In simple words, the scope of a function means if it can be called from other procedures or not. A UDF can have two different types of scopes.
1. Public
You can make your custom function public so that you can use it in all the worksheets of the workbook and call it from procedures in other modules. To make a Function public you just need to use the word “Public”, just like below.

A function is public by default if you don’t make it private, so all the examples we have covered are public.
2. Private
When you make a function private, you can only use it in the procedures of the same module.

Let’s say if you have your UDF in “Module1” you can only use it in procedures you have in “Module1”. And it won’t appear in the function list of the worksheet (when you use = sign and try to type the name) but you can still use it by typing its name and specifying arguments.
Limitations of User-Defined Function [UDF]
UDFs are super useful. But they are limited in some situations. Here are a few things which I want you to note down and remember while creating a custom function in VBA.
- You can’t change, delete, or format cells and a range by using a custom function.
- It also can’t move, rename, delete, or add worksheets to a workbook.
- It can’t change another cell’s value.
- It also can’t make changes to any of the environment options.
Is there any difference between an In-Built Function and a User Defined Function?
I’m glad you asked. Well, to answer this question I want to share some of the points which I believe are important for you to know.
- Slower Than In-Built: If you compare the speed of in-built functions and VBA functions, you’ll find the in-built ones are faster. The reason behind this is that in-built functions are compiled into Excel itself, while a UDF runs through the VBA engine.
- Hard to Share Files: We often share files over email and the cloud, so if you are using any custom functions, you need to share the file as a macro-enabled workbook (.xlsm) or share the add-in (“xlam” format) so that the other person can also use your custom function.
But as I said above in “Why You Should Create a Custom Excel Function” there are some specific situations when you can go for a VBA custom function.
Make a UDF Recalculate with Application.Volatile
By default, Excel recalculates a UDF only when one of its arguments changes. So, a function like myPath, which has no arguments, won’t update on its own when you save the file to a new folder. To make it recalculate every time the sheet calculates, add Application.Volatile as its first line:
Function myPath() As String
Application.Volatile
myPath = ActiveWorkbook.FullName
End Function
Use it only when you need it, as volatile functions recalculate on every change and can slow down a big workbook. You can also press Ctrl + Alt + F9 to recalculate all the formulas once.
Add a Description to Your UDF
In-built functions show a short description in the Insert Function dialog box. You can do the same for your UDF with Application.MacroOptions. Run the following code once, and then save the workbook:
Sub addUDFDescription()
Application.MacroOptions _
Macro:="myDayName", _
Description:="Returns the day name from a date.", _
ArgumentDescriptions:=Array("A date or a cell with a date")
End Sub
Frequently Asked Questions
Why does my UDF show the #NAME? error?
Excel can’t find the function. Check that the code is in a standard module (not a sheet module), that macros are enabled, and that the function name is spelled the same way. If the UDF is in another open workbook, like your Personal Macro Workbook, put the file name in front of it: =PERSONAL.XLSB!myDayName(A2).
How do I save a workbook with a UDF?
Save it as an Excel Macro-Enabled Workbook (.xlsm). If you save it as a normal .xlsx file, Excel removes the VBA code, and the formulas show #NAME? the next time you open the file.
Can a UDF return more than one value?
Yes. If the function returns an array, Excel 365 and Excel 2021 spill the values into the cells next to it. In older versions, select the output range first and enter the formula with Ctrl + Shift + Enter.
Conclusion
Creating a User Defined Function is simple. All you need to do is use “Function” before the name to define it as a function, add arguments, define the arguments data type, and then define the data type for the return value.

In the end, add code to calculate the value which you want to get in return from the function. This guide which I have shared with your today is the simplest one to learn how to create a custom function in VBA and I’m sure you have found it useful.
But now, tell me one thing.
UDFs are useful, what do you think?
Please share your views with me in the comment section. I’d love to hear from you, and please, don’t forget to share this post with your friends, I am sure they will appreciate it.
Related Tutorials
- VBA Functions List – Explained with Examples
- How to Run a Macro in Excel
- How to use IF Statement in VBA
- How to Work with Ranges and Cells in VBA
- VBA Comment
- Add New Sheet using a VBA Code
VBA is one of the Advanced Excel Skills, and if you are getting started with VBA, make sure to check out there (What is VBA and Useful Macro Examples and VBA Codes).
I createdd your initial example (MyDayName), but when I call it in Excel I get the error message “Invalid Name Error”. Can you tell me what I am doing wrong?
share the screen shot of the code you have pasted.
Thanks for this great article.
I find your course extremely frustrating! Right from the getgo;- 1) Developer tab, VBE. Mine opens a blank window with Microsoft Visual Basic – Book1.
No matter which way I go, it does not look like yours. If this is how you start, I don’t want to know what the next few pages are like!
Really sad to hear that. Which version and system you are using Excel on?
Good Morning.. I wish to give You my most warm Felicitations for Sharing All the Content of these Courses.. I have learned VBA and it has been of Grest help to Overcome the Enclosure during the CoVid Lock-In..My only request is to ask You.. Do you have a Downloadable version.. sometimes The Internet Fails or becomes Intermitent and it is very dificult to login
. Again, Thank you very much..
Yes
Good work 🙂 But I have a question: If I create a UDF for my colleague, how can I make it user-friendly? With In-Built functions it’s easy, when I start writing a function and open the bracket, it shows needed arguments. Is it possible for UDF function to work in the same way? My function has 3 arguments, how can user know what kind of arguments and in which order he has to put? I know it’s possible to go by Insert Function but I ‘m not satisfied.
Thanks for the article.
Is it possible to create an UDF that returns an array that I can use in a cell validation criteria formula ( list or … ) ?
Very well done
Thanks.
How I can put help texts for my own functions, to guide users the arguments type.
Love the guide and the content, great stuff. Just a heads up that the links in the Table of Contents did not work for me. It didnt move to those particular bookmarks on the page. Although I realized all I needed to do was scroll down, just wanted to make you aware. I use Firefox 62.0
Hey, Damien. Can you try it again?