Using a Function
You can't "run" a user-defined function in the same way that you run a command macro.
Instead, you use the function either as part of a command macro (or even as part of another function), or within the application itself.
To use a function in a command macro, you create a separate VBA statement that includes
the function name as well as any arguments it requires.
(This is known as calling the function.)
Here's a simple example:
Public Sub MonthMarkTest1() MsgBox MonthMark (100000, 90000) End Sub
This Sub procedure calls the MonthMark function and supplies it with the values 100000 and 90000 for the Sales and Expenses arguments, respectively. The MsgBox function displays the result in a dialog box.
To use a function in an application, you include it as part of some other calculation. This is most useful in Excel, where you can employ a user-defined function within a worksheet formula. The easiest way to do this is to enter the function into the cell the same way you would any of Excel's built-in functions. In other words, enter the name of the function and then the necessary arguments enclosed in parentheses. Here's a sample formula that uses the MonthMark function and assumes the Sales and Expenses values are in cells B1 and B2, respectively.
=MonthMark(B1, B2)
You can also use the Function wizard to insert a user-defined function. Here are the steps to follow:
- Click the cell into which you want to insert the user-defined function.
- Choose Formulas, Insert Function to display the Insert Function dialog box.
- In the Or Select a Category list, click User Defined. Excel displays a list of your userdefined functions.
- Click the function you want to insert and then click OK. The Function Arguments dialog box appears.
- Specify values or cell addresses for the function arguments and then click OK. Excel inserts the function.
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