A fast and secure browser thats designed for Windows 10
Although Excel includes a multitude of built-in worksheet functions, chances are it doesnt have a function for every type of calculation you perform. The designers of Excel couldnt possibly anticipate every users calculation needs. Instead, Excel provides you with the ability to create custom functions, which are explained in this article.
Custom functions, like macros, use theVisual Basic for Applications (VBA)programming language. They differ from macros in two significant ways. First, they useFunctionprocedures instead ofSubprocedures. That is, they start with aFunctionstatement instead of aSubstatement and end withEnd Functioninstead ofEnd Sub. Second, they perform calculations instead of taking actions. Certain kinds of statements, such as statements that select and format ranges, are excluded from custom functions. In this article, youll learn how to create and use custom functions. To create functions and macros, you work with theVisual Basic Editor (VBE), which opens in a new window separate from Excel.
Suppose your company offers a quantity discount of 10 percent on the sale of a product, provided the order is for more than 100 units. In the following paragraphs, well demonstrate a function to calculate this discount.
The example below shows an order form that lists each item, quantity, price, discount (if any), and the resulting extended price.
To create a custom DISCOUNT function in this workbook, follow these steps:
PressAlt+F11to open the Visual Basic Editor (on the Mac, pressFN+ALT+F11), and then clickInsertModule. A new module window appears on the right-hand side of the Visual Basic Editor.
Copy and paste the following code to the new module.
DISCOUNT = Application.Round(Discount, 2)
Note:To make your code more readable, you can use theTabkey to indent lines. The indentation is for your benefit only, and is optional, as the code will run with or without it. After you type an indented line, the Visual Basic Editor assumes your next line will be similarly indented. To move out (that is, to the left) one tab character, pressShift+Tab.
Now youre ready to use the new DISCOUNT function. Close the Visual Basic Editor, select cell G7, and type the following:
Excel calculates the 10 percent discount on 200 units at $47.50 per unit and returns $950.00.
In the first line of your VBA code, Function DISCOUNT(quantity, price), you indicated that the DISCOUNT function requires two arguments,quantityandprice. When you call the function in a worksheet cell, you must include those two arguments. In the formula =DISCOUNT(D7,E7), D7 is thequantityargument, and E7 is thepriceargument. Now you can copy the DISCOUNT formula to G8:G13 to get the results shown below.
Lets consider how Excel interprets this function procedure. When you pressEnter, Excel looks for the nameDISCOUNTin the current workbook and finds that it is a custom function in a VBA module. The argument names enclosed in parentheses,quantityandprice, are placeholders for the values on which the calculation of the discount is based.
The If statement in the following block of code examines thequantityargument and determines whether the number of items sold is greater than or equal to 100:
If the number of items sold is greater than or equal to 100, VBA executes the following statement, which multiplies thequantityvalue by thepricevalue and then multiplies the result by 0.1:
The result is stored as the variableDiscount. A VBA statement that stores a value in a variable is called anassignmentstatement, because it evaluates the expression on the right side of the equal sign and assigns the result to the variable name on the left. Because the variableDiscounthas the same name as the function procedure, the value stored in the variable is returned to the worksheet formula that called the DISCOUNT function.
Ifquantityis less than 100, VBA executes the following statement:
Finally, the following statement rounds the value assigned to theDiscountvariable to two decimal places:
Discount = Application.Round(Discount, 2)
VBA has no ROUND function, but Excel does. Therefore, to use ROUND in this statement, you tell VBA to look for the Round method (function) in the Application object (Excel). You do that by adding the wordApplicationbefore the word Round. Use this syntax whenever you need to access an Excel function from a VBA module.
A custom function must start with a Function statement and end with an End Function statement. In addition to the function name, the Function statement usually specifies one or more arguments. You can, however, create a function with no arguments. Excel includes several built-in functionsRAND and NOW, for examplethat dont use arguments.
Following the Function statement, a function procedure includes one or more VBA statements that make decisions and perform calculations using the arguments passed to the function. Finally, somewhere in the function procedure, you must include a statement that assigns a value to a variable with the same name as the function. This value is returned to the formula that calls the function.
The number of VBA keywords you can use in custom functions is smaller than the number you can use in macros. Custom functions are not allowed to do anything other than return a value to a formula in a worksheet, or to an expression used in another VBA macro or function. For example, custom functions cannot resize windows, edit a formula in a cell, or change the font, color, or pattern options for the text in a cell. If you include action code of this kind in a function procedure, the function returns the VALUE! error.
The one action a function procedure can do (apart from performing calculations) is display a dialog box. You can use anInputBoxstatement in a custom function as a means of getting input from the user executing the function. You can use aMsgBoxstatement as a means of conveying information to the user. You can also use custom dialog boxes, orUserForms, but thats a subject beyond the scope of this introduction.
Even simple macros and custom functions can be difficult to read. You can make them easier to understand by typing explanatory text in the form of comments. You add comments by preceding the explanatory text with an apostrophe. For example, the following example shows the DISCOUNT function with comments. Adding comments like these makes it easier for you or others to maintain your VBA code as time passes. If you need to make a change to the code in the future, youll have an easier time understanding what you did originally.
An apostrophe tells Excel to ignore everything to the right on the same line, so you can create comments either on lines by themselves or on the right side of lines containing VBA code. You might begin a relatively long block of code with a comment that explains its overall purpose and then use inline comments to document individual statements.
Another way to document your macros and custom functions is to give them descriptive names. For example, rather than name a macroLabels, you could name itMonthLabelsto describe more specifically the purpose the macro serves. Using descriptive names for macros and custom functions is especially helpful when youve created many procedures, particularly if you create procedures that have similar but not identical purposes.
How you document your macros and custom functions is a matter of personal preference. Whats important is to adopt some method of documentation, and use it consistently.
To use a custom function, the workbook containing the module in which you created the function must be open. If that workbook is not open, you get a NAME? error when you try to use the function. If you reference the function in a different workbook, you must precede the function name with the name of the workbook in which the function resides. For example, if you create a function called DISCOUNT in a workbook called Personal.xlsb and you call that function from another workbook, you must type=personal.xlsb!discount(), not simply=discount().
You can save yourself some keystrokes (and possible typing errors) by selecting your custom functions from the Insert Function dialog box. Your custom functions appear in the User Defined category:
An easier way to make your custom functions available at all times is to store them in a separate workbook and then save that workbook as an add-in. You can then make the add-in available whenever you run Excel. Heres how to do this:
After you have created the functions you need, clickFileSave As.
In Excel 2007, click theMicrosoft Office Button, and clickSave As
In theSave Asdialog box, open theSave As Typedrop-down list, and selectExcel Add-In. Save the workbook under a recognizable name, such asMyFunctions, in theAddInsfolder. TheSave Asdialog box will propose that folder, so all you need to do is accept the default location.
After you have saved the workbook, clickFileExcel Options.
In Excel 2007, click theMicrosoft Office Button, and clickExcel Options.
In theExcel Optionsdialog box, click theAdd-Inscategory.
In theManagedrop-down list, selectExcel Add-Ins. Then click theGobutton.
In theAdd-Insdialog box, select the check box beside the name you used to save your workbook, as shown below.
After you have created the functions you need, clickFileSave As.
In theSave Asdialog box, open theSave As Typedrop-down list, and selectExcel Add-In. Save the workbook under a recognizable name, such asMyFunctions.
After you have saved the workbook, clickToolsExcel Add-Ins.
In theAdd-Insdialog box, select the Browse button to find your add-in, clickOpen, then check the box beside your Add-In in theAdd-Ins Availablebox.
After you follow these steps, your custom functions will be available each time you run Excel. If you want to add to your function library, return to the Visual Basic Editor. If you look in the Visual Basic Editor Project Explorer under a VBAProject heading, you will see a module named after your add-in file. Your add-in will have the extension .xlam.
Double-clicking that module in the Project Explorer causes the Visual Basic Editor to display your function code. To add a new function, position your insertion point after the End Function statement that terminates the last function in the Code window, and begin typing. You can create as many functions as you need in this manner, and they will always be available in the User Defined category in theInsert Functiondialog box.
This content was originally authored by Mark Dodge and Craig Stinson as part of their bookMicrosoft Office Excel 2007 Inside Out. It has since been updated to apply to newer versions of Excel as well.
You can always ask an expert in theExcel Tech Community, get support in theAnswers community, or suggest a new feature or improvement onExcel User Voice.