18.11.2014 Views

Microsoft Office

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Part VI<br />

Programming Excel with VBA<br />

An Introductory Example<br />

The process of creating custom functions is relatively easy, once you understand VBA. Without further ado,<br />

here’s an example of a VBA function procedure. This function is stored in a VBA module, which is accessible<br />

from the VB Editor.<br />

A custom function<br />

This example function, named NumSign, uses one argument. The function returns a text string of Positive if<br />

its argument is greater than zero, Negative if the argument is less than zero, and Zero if the argument is<br />

equal to zero. The function is shown in Figure 40.1.<br />

FIGURE 40.1<br />

A simple custom worksheet function.<br />

You can, of course, accomplish the same effect with the following worksheet formula, which uses a nested<br />

IF function:<br />

=IF(A1=0,”Zero”,IF(A1>0,”Positive”,”Negative”))<br />

Many would agree that the custom function solution is easier to understand and to edit than the worksheet<br />

formula.<br />

Using the function in a worksheet<br />

When you enter a formula that uses the NumSign function, Excel executes the function to get the result.<br />

This custom function works just like any built-in worksheet function. You can insert it in a formula by<br />

choosing Formulas ➪ Function Library ➪ Function Wizard, which displays the Insert Function dialog box.<br />

(Custom functions are listed in the User Defined category.) When you select the function from the list, you<br />

can then use the Function Arguments dialog box to specify the arguments for the function, as shown in<br />

Figure 40.2. You also can nest custom functions and combine them with other elements in your formulas.<br />

704

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!