Excel 2007 Formulas (Mr. Spreadsheets Bookshelf)

In this section, I discuss some of the technical details that apply to Function procedures. These are general guidelines for declaring functions, naming functions, using custom functions in formulas, and using arguments in custom functions.

Declaring a Function

The official syntax for declaring a function is as follows:

[Public | Private][Static] Function name ([arglist]) [As type] [statements] [name = expression] [Exit Function] [statements] [name = expression] End Function

The following list describes the elements in a Function procedure declaration:

Choosing a Name for Your Function

Each function must have a unique name, and function names must adhere to a few rules:

Using Functions in Formulas

Using a custom VBA function in a worksheet formula is like using a built-in worksheet function except that you must ensure that Excel can locate the Function procedure. If the Function procedure is in the same workbook as the formula, you don't have to do anything special. If it's in a different workbook, you may have to tell Excel where to find it. You can do so in three ways:

Figure 23-2: Use the References dialog box to create a reference to a project that contains a custom VBA function.

Tip 

By default, all projects are named VBAProject-and that's the name that appears in the Available References list in the References dialog box. To make sure that you select the correct project in the References dialog box, keep your eye on the bottom of the dialog box, which shows the workbook name for the selected item. Better yet, change the name of the project to be more descriptive. To change the name, select the project, press F4 to display the Properties window, and then change the Name property to something other than VBAProject. It's best to use a unique name because Excel will not let you create two references with the same name.

Note 

None of these three methods will cause the function name to appear in the Formula AutoComplete drop-down. Formula AutoComplete works only when the formula is entered into the workbook that contains the custom function. This is a known bug in the initial release of Excel 2007, and the problem may be corrected in an update.

Using Function Arguments

Custom functions, like Excel's built-in functions, vary in their use of arguments. Keep the following points in mind regarding VBA Function procedure arguments:

Cross Ref 

See Chapter 25 for examples of functions that use various types of arguments.

All cells and ranges that are used by a function should be passed as arguments. In other words, a Function procedure should never contain direct references to cells or ranges.

Категории