18.11.2014 Views

Microsoft Office

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Part VI<br />

Programming Excel with VBA<br />

What a Function Can’t Do<br />

Almost everyone who starts creating custom worksheet functions using VBA makes a fatal mistake: They try<br />

to get the function to do more than is possible.<br />

A worksheet function returns a value, and the function must be completely “passive.” In other words, the<br />

function can’t change anything on the worksheet. For example, you can’t develop a worksheet function that<br />

changes the formatting of a cell. (Every VBA programmer has tried, and not one of them has been successful!)<br />

If your function attempts to perform an action that isn’t allowed, the function simply returns an error.<br />

VBA functions that aren’t used in worksheet formulas can do anything that a regular Sub procedure can do —<br />

including changing cell formatting.<br />

To create a custom function, follow these steps:<br />

1. Activate the VB Editor (press Alt+F11).<br />

2. Select the workbook in the Project window.<br />

3. Choose Insert ➪ Module to insert a VBA module. (Or you can use an existing module.)<br />

4. Enter the keyword Function followed by the function’s name and a list of the arguments (if<br />

any) in parentheses.<br />

5. Insert the VBA code that performs the work — and make sure that the variable corresponding<br />

to the function’s name has the appropriate value when the function ends. (This is the<br />

value that the function returns.)<br />

6. End the function with an End Function statement.<br />

Function names that are used in worksheet formulas must adhere to the same rules as variable names.<br />

Executing Function Procedures<br />

You can execute a Sub procedure in many ways, but you can execute a Function procedure in just two ways:<br />

n<br />

n<br />

Call it from another VBA procedure.<br />

Use it in a worksheet formula.<br />

Calling custom functions from a procedure<br />

You can call custom functions from a procedure just as you call built-in VBA functions. For example, after<br />

you define a function called CalcTax, you can enter a statement such as the following:<br />

Tax = CalcTax(Amount, Rate)<br />

This statement executes the CalcTax custom function with Amount and Rate as its arguments. The function’s<br />

result is assigned to the Tax variable.<br />

706

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

Saved successfully!

Ooh no, something went wrong!