Excel UDF Tutorial
Microsoft Excel supports macros but it also supports library functions, known as User Defined Functions (UDF). Library functions are less risky than macros because they must return a value to a cell. This is a quick tutorial, mostly for my students, but as usual for anybody who’s interested.
Microsoft Excel User Defined Functions (UDFs) are different than standard VBA macros. They’re behavior is restricted. You can’t access other cells in a workbook, and may only return a value (also known as an expression) to the cell that uses the formula. That having been said, they can dramatically hide the complexity of mega-formulas and remove them from the editing control of users.
Here are the steps to configure your Excel 2007 environment to work with Visual Basic for Applications (VBA) and UDFs. They show you how to display the developer ribbon, open a module for editing, save VBA code into a library (*.xlam file), and add the library file as an “Add-in” library to your Excel 2007 installation. The name of the library will be the same as the Workbook where you created it.
- Displaying Excel’s Developer Tab
There are four steps to make this visible. They are:
- Choose the Office Button. You’ll see the following:
- Click the Excel Options button.
- Click the Popular tab if not highlighted (it’s the default). Inside the right side pane, click the Show Developer tab in the Ribbon check box to enable it, and click the OK button to set it.
- Click the Developer ribbon tab. Click the left most icon to launch the Visual Basic Editor screen.
- Open a Module in the Visual Basic Editor by clicking the Insert menu item and choosing the Module element.
- Copy the following function definition into the open Module. The name of the UDF will be the case-sensistive name of the function in the VBA module. That means you’ll now have a newSerialDate function in your list of functions when you click the insert function button.
I struggled to come up with a simple function to illustrate this and how you debug UDFs. A word to the wise, you can’t use a numeric variable inside a MsgBox by itself. If you attempt it, Excel will return a #Value! error in the cell where you call the UDF. You must include a numeric variable as an argument (also known as a call parameter) to the CStr() function. An example is: Cstr(myVariable). You call this sample function by entering:
=monthEnd(cell_reference)
When you pass a date (actually an integer in the spreadsheet), the function handles it as a string. While no data type is assigned the dateIn variable in the example, variables without an explicit data type are always of the Variant data type. The Variant data type is a master data type and can hold any other type, which makes it like the Object data type in Java.
This program parses the string, then uses the DateSerial() function to return it as a number. It’s critical to note that the last line returns the value in the newSerialDate variable, and that variable must always be the function name. Place a single quote mark before all MsgBox() function calls after verifying that the function works.
Public Function newSerialDate(dateIn) ' Define local variables. Dim day As String Dim month As String Dim year As String Dim startPosition As Integer Dim endPosition As Integer Dim length As Integer ' Initialize local variables and parse the month from the left. startPosition = 1 endPosition = InStr(startPosition, dateIn, "/") month = Left(dateIn, endPosition - 1) ' This is a debugging tool to track variables during execution. MsgBox ("Month [" + month + "]") ' Shift the start position and parse the day from the middle. startPosition = endPosition + 1 endPosition = InStr(startPosition, dateIn, "/") day = Mid(dateIn, startPosition, endPosition - startPosition) ' This is a debugging tool to track variables during execution. MsgBox ("Day [" + day + "]") ' Get the remainder of the string. startPosition = endPosition length = Len(dateIn) - startPosition year = Right(dateIn, length) ' This is a debugging tool to track variables during execution. MsgBox ("Year [" + year + "]") ' Return a value from a User Defined Function (UDF) by using ' the function name as the return variable. newSerialDate = DateSerial(year, month, day) End Function
Aside from the fact that all this parsing isn’t really necessary because the problem is much simpler and cleaner. At least, it becomes so when you understand the breadth of built-in functions in VBA. You can solve the problem by designating the formal parameter as a Double like the example below.
Function newSerialDate(dateIn As Double) newSerialDate = dateIn End Function
Alternatively, you can accept a Variant, which maps to a String. Then, you convert it to a Date like this:
Function newSerialDate(dateIn) newSerialDate = DateValue(dateIn) End Function
- Create the following spreadsheet, the formula values are noted below the screen shot. You should be able to copy and past them into the spreadsheet. After you’ve created the spreadsheet, entering a new date in cell
A1causes the UDF to run. When the UDF runs “as-is”, you’ll see message dialog boxes that show values set during runtime.
| Spreadsheet Functions | |
|---|---|
| Cell | Formula |
| A2 | =newSerialDate(A1) |
| C1 | =VLOOKUP(TYPE(A1),$E$3:$F$7,MATCH("Meaning",$E$2:$F$2,FALSE)) |
| C2 | =VLOOKUP(TYPE(A2),$E$3:$F$7,MATCH("Meaning",$E$2:$F$2,FALSE)) |
- You can now save this as an Add In library but comment out those debug
MsgBox()function calls. Click the Office Button and click SaveAs in the menu, then accept Excel Workbook initially. When you get to the SaveAs dialog, choose Excel Add-In as the file type. Below is a screen capture of the drop down selection box.
- Open a new Excel Workbook. Click the Excel Options button. Click the Add-Ins tab. Inside the right side pane, make sure the Manage drop down says Excel Add-ins before you click the Go button.
- Check the Samplefunction check box as shown below. Samplefunction is the name of the Workbook that contains the module, and it is saved as an
*.xlamfile. Click the OK button to add the library. You’ve now created, and added an Add-In library to your new spreadsheet. It will create aSampleFunction.xlamfile in the users directory.
The file is found by default in:
C:\Users\UserName\AppData\Roaming\Microsoft\AddIns
As always, I hope this is helpful to a few folks.









[...] an example LPAD() User Defined Function [...]
Learn how to LPAD a string in Excel | MacLochlainns Weblog
31 May 10 at 11:34 am
[...] You can replace the compound logic checking for the value of the second element of a string with the
ISLIKEfunction. [...]LIKE operation in Excel
4 Jun 10 at 11:28 am
Quite informative for a newbie. I am actually looking for help to create a UDF for myself with the purpose of comparing a column containing dates on one sheet with a reference date on another sheet and correspondingly pick up values from a second column on the same sheet as column of dates. Can you help me ??
Rituraj
7 Jun 10 at 2:33 am
You need to pass the cell references as call parameters to your UDF. You reference call parameters as an absolute, mixed, or relative reference. You can use a cell from another worksheet with syntax like this for a relative cell reference:
… another workbook with syntax that includes a mixed cell reference, like:
=SomeUDFName('C:\My Documents\[WorkbookName.xlsx]Sheet1!A$1)… or a network qualified path with absolute notation, like:
=SomeUDFName('\\SomeServer\SharedFiles\[WorkbookName.xlsx]Sheet1!$A$1)A UDF can only return a value to a cell, or a value as a call argument to another function call. Only macros have the ability of accessing interactively cells in the workbook during processing. More or less, any UDF is an isolated function that takes inputs, consumes them, and produces an output.
maclochlainn
7 Jun 10 at 9:20 pm
will this function displayed in auto formula list
sundar
2 Aug 10 at 1:21 am
It appears if you start to type it but not in the generic poplist.
maclochlainn
9 Aug 10 at 8:11 am
[...] UDFs can simplify our lives for routine [...]
UDF for a VLOOKUP
6 Sep 10 at 3:17 pm
[...] some interesting parameter validation rules for Excel User-Defined Functions (UDFs). I found that optional values are suppressed when you pass a cell reference that points to an empty [...]
UDF Parameters
31 Oct 10 at 12:07 am
If I write a really simple function such as:
‘get the first position of a single character in a string
Public Function GetCharPos(ByVal c As String, ByRef s As String) As Integer
GetCharPos = InStr(1, s, c)
End Function
why can’t I call it in the Immediate window with:
? GetCharPos(” “, “Mr John Doe”)
More generally, I can’t see any of my procs and funcs. I’m using Excel 2007.
Thanks
Charlie
Charlie Howard
5 Jul 11 at 5:20 am
I freaking love u!!! thank u
betty
13 Oct 11 at 3:20 pm
Informative description provided
Thanks
kj
17 Nov 11 at 2:19 am
Thanks the best discussion I’ve found anywhere. One question: If I want to modify a UDF, can I simply open it, modify it in the VBA editor, and then save?
Michael Trombetta
10 Feb 12 at 3:22 pm
Yes, you can in a workbook. You should always keep a separate copy of the macro libraries, that’s what you can dynamically edit. If you’ve added a copy as a library, you must first remove it (by unchecking the box in the Add-Ins dialog) and then delete it from the physical location on the file system; and then you can add it back with modifications.
You really shouldn’t have to delete it from my opinion but some folks report that changes don’t seem to take effect. My guess is that they’ve got two files or a cache read problem but I’ve never had the problem. If you follow the steps above you shouldn’t either. A little extra work may save time debugging it.
maclochlainn
10 Feb 12 at 8:05 pm
Hi,
Is it possible to call one userdefined functions inside another user defined function? I have a UDF written by a dfferent user which i want to call in a UDF i am writting.
I have tried
call.UDFtoBeCalled(parameter1, parameter 2)
Buth this did not appear to work
Thanks in advance,
DK
DK
12 Feb 12 at 5:21 pm
If the function is in the same module, you only need the module name. Just remember, that unlike a subroutine a function returns a value. The means if the UDF returns a string, you’d need to assign its return value to a local variable. I borrowed the following from another post of mine. The first example declares an
ISLIKEfunction.A quick example of how to use the
ISLIKEfunction replaces the logic in the following:With this, where the call to the function simplifies the logic of the
ElseIFcomparison:In your case, I’ve a hunch it’ll be something like this:
Hope this helps.
maclochlainn
12 Feb 12 at 10:08 pm