Create a User Defined Function in Microsoft Excel
Even when Excel has a lot, probably hundreds, of built in functions like SUM, VLOOKUP, LEFT, and so on, once you start using Excel for more complicated tasks, you will often find that you need a function that doesn't exist. Don't worry, you're not lost at all, all you need is to create the function yourself.
Contents
Steps
- Create a new workbook or open the workbook in which you want to use your newly created User Defined Function (UDF).
- Open the Visual Basic Editor which is built into Microsoft Excel by going to Tools->Macro->Visual Basic Editor (or pressing Alt+F11).
- Add a new Module to your workbook by clicking in the button shown. You can create the user defined function in the Worksheet itself without adding a new module, but that will make you unable to use the function in other worksheets of the same workbook.
- Create the "header" or "prototype" of your function. It has to have the following structure:
public function "The Name Of Your Function" (param1 As type1, param2 As type2 ) As return Type
It can have as many parameters as you want, and their type can be any of Excel's basic data types or object types as Range. You may think of parameters as the "operands" your function will act upon. For example, when you say SIN(45) to calculate the Sine of 45 degree, 45 will be taken as a parameter. Then the code of your function will use that value to calculate something else and present the result. - Add the code of the function making sure you 1) use the values provided by the parameters; 2) assign the result to the name of the function; and 3) close the function with "end function".
Learning to program in VBA or in any other language can take some time and a detailed tutorial. However, functions usually have small code blocks and use very few features of a language. The more useful elements of the VBA language are:- The If block, which allows you to execute a part of the code only if a condition is met. For example:
Public Function Course Result(grade As Integer) As String
If grade >= 5 Then
CourseResult = "Approved"
Else
CourseResult = "Rejected"
End If
End Function
Notice the elements in an If code block:IF condition THEN code ELSE code END IF
. The Else keyword along with the second part of the code are optional. - The Do block, which executes a part of the code While or Until a condition is met. For example:
Public Function IsPrime(value As Integer) As Boolean
Dim i As Integer
i = 2
IsPrime = True
Do
If value / i = Int(value / i) Then
IsPrime = False
End If
i = i + 1
Loop While i < value And IsPrime = True
End Function
Notice the elements again:DO code LOOP WHILE/UNTIL condition
. Notice also the second line in which a variable is "declared". You can add variables to your code so you can use them later. Variables act as temporary values inside the code. Finally, notice the declaration of the function as BOOLEAN, which is a datatype that allows only the TRUE and FALSE values. This method of determining if a number is prime is by far not the optimal, but I've left it that way to make the code easier to read. - The For block, which executes a part of the code a specified number of times. For example:
Public Function Factorial(value As Integer) As Long
Dim result As Long
Dim i As Integer
If value = 0 Then
result = 1
ElseIf value = 1 Then
result = 1
Else
result = 1
For i = 1 To value
result = result * i
Next
End If
Factorial = result
End Function
Notice the elements again:FOR variable = lower limit TO upper limit code NEXT
. Also notice the added ElseIf element in the If statement, which allows you to add more options to the code that is to be executed. Finally, notice the declaration of the function and the variable "result" as Long. The Long datatype allows values much larger than Integer.
Shown below is the code for a function that converts small numbers into words.
- The If block, which allows you to execute a part of the code only if a condition is met. For example:
- Go back to your workbook and use the function by starting the content of a cell with an equal sign followed by the name of your function. Append to the name of the function an opening parenthesis, the parameters separated by commas and a final closing parenthesis. For example:
=NumberToLetters(A4)
You can also use your user defined formula by looking for it in the User Defined category in the Insert Formula wizard. Just click in the Fx button located to the left of the formula bar.
The parameters can be of three types:- Constant values typed directly in the cell formula. Strings have to be quoted in this case.
- Cell references like B6 or range references like A1:C3 (the parameter has to be of the Range datatype)
- Other functions nested inside your function (your function can also be nested inside other functions). I.e.: =Factorial(MAX(D6:D8))
- Verify the result is Ok after using the function several times to ensure it handles different parameter values correctly:
Tips
- Whenever you write a block of code inside a control structure like If, For, Do, etc. make sure you indent the block of code using a few blank spaces or tab (the style of indentation is up to you). That will make your code easier to understand and you'll find a lot easier to spot errors and make improvements.
- If you don't know how to write the code for a function, read How to Write a Simple Macro in Microsoft Excel.
- Sometimes, a function may not require all the parameters to calculate a result. In that case you can use the keyword Optional before the name of the parameter in the function header. You can use the function IsMissing(parameter_name) inside the code to determine if the parameter was assigned a value or not.
- Use a name that's not already defined as a function name in Excel or you'll end up being able to use only one of the functions.
- Excel has many built in functions and most calculations can be done by using them either independently or in combination. Make sure you go through the list of available functions before you start coding your own. Execution may be faster if you use the built in functions.
Warnings
- Due to security measures, some people may disable macros. Make sure you let your colleagues know the book you're sending them has macros and that they can trust they're not going to damage their computers.
- The functions used in this article are, by no means, the best way to solve the related problems. They were used here only to explain the usage of the control structures of the language.
- VBA, as any other language, has several other control structures besides Do, If and For. Those have been explained here only to clarify what kind of things can be done inside the function source code. There are many online tutorials available where you can learn VBA.