Writing a User-Defined Function
When you record a macro, VBA always puts the code inside a command macro. Unfortunately, there is no way to record a user-defined function; you have to write them out by hand. Fortunately, the process is very similar to creating a command macro from scratch. Here are the general steps to follow to write a user-defined function:
- Open the module you want to use for the function.
- Place the insertion point where you want to start the function. (Make sure the insertion point isn't inside an existing macro.)
- Choose Insert, Procedure to open the Add Procedure dialog box.
- Use the Name text box to type the function's name. The guidelines you must follow are the same as those for a command macro: The name must be 255 characters or fewer; the first character must be a letter or an underscore (_); and you can't use spaces or periods.
- In the Type group, click the Function option.
- Click OK. VBA adds the following code to the module (where ProcedureName is the name you typed in step 3):
Public Function ProcedureName() End Function
- Between the Public Function and End Function lines, type the VBA statements you want to include in the function. Press Enter after each statement to start a new line.
- Be sure to include a statement that defines the return value. That statement should consist of the function name, followed by an equals sign (=), followed by the return value.
Figure shows an example user-defined function that calculates and returns a result, using a single VBA statement:
MonthMark = (Sales - Expenses) / Sales
Here, Sales and Expenses are the arguments that get passed to the function. The function subtracts the Expenses value from the Sales value, and then divides by Sales to return the gross margin.
In this tutorial:
- Writing Your Own Macros
- Activating the Ribbon's Developer Tab
- Displaying the Visual Basic Editor
- Touring the Visual Basic Editor
- Understanding VBA Procedures
- Creating a Command Macro
- Entering VBA Statements
- Creating a User-Defined Function
- Understanding User-Defined Functions
- Writing a User-Defined Function
- Using a Function
- Advantage of VBA IntelliSense
- Shutting Down the Visual Basic Editor