Creating a Custom Function

With VBA you can automate worksheet and chart processes and also create custom functions. Functions generated with VBA procedures are similar to the built-in functions used in worksheets. A function consists of a unique name, parentheses, and usually one or more arguments separated by a comma. A function usually returns a single value as a result. The syntax is Function Name(Arg1, Arg2,...). The number of arguments depends on the task and the use of the function. Custom functions are used from a cell in a worksheet, the same way you would use any built-in Excel function, such as SUM(Number1, Number2,...).

To create a function, you need the following:

Anyone can use the function with its name and arguments from the worksheet, but the algorithm is hidden from the user. However, a normal user is unlikely to care, as long as the function works properly.

A VBA procedure to create a function involves the following:

The part between the Function key word and the final End Function statement is called a function block. The remainder of this chapter presents a few examples to illustrate this process.

The AreaCircle() example explains the following:

By using the AreaQuad() example, you will learn the following:

The AreaSect() function serves as an example for the following:

By using the DigitSum() example, you will learn the following:

The AreaCircle1() example explains the following:

Finally, you learn how to use the Function Wizard and the Excel add-ins to create your own functions that you can use in your worksheets.

Note

For the following examples, you should open the Developer tab if you use Excel 2010 or Excel 2007. In Excel 2010, on the File tab, click Options and then Customize Ribbon. Select All Tabs or Main Tabs on the right, below the ribbon text. Select the Developer check box in the list. In Excel 2007, click the Office button and then Excel Options. Make sure that the Popular category is selected. Select the Show Developer Tab In The Ribbon check box. Click OK to display the Developer tab in the ribbon.