11.08.2013 Views

Excel's Formula - sisman

Excel's Formula - sisman

Excel's Formula - sisman

SHOW MORE
SHOW LESS

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

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

Chapter 25: VBA Custom Function Examples 681<br />

Controlling function recalculation<br />

When you use a custom function in a worksheet formula, when is it recalculated?<br />

Custom functions behave like Excel’s built-in worksheet functions. Normally, a custom function is<br />

recalculated only when it needs to be recalculated — that is, when you modify any of a function’s<br />

arguments — but you can force functions to recalculate more frequently. Adding the following<br />

statement to a Function procedure makes the function recalculate whenever the<br />

workbook is recalculated:<br />

Application.Volatile True<br />

The Volatile method of the Application object has one argument (either True or False).<br />

Marking a Function procedure as “volatile” forces the function to be calculated whenever calculation<br />

occurs in any cell in the worksheet.<br />

For example, the custom STATICRAND function presented in this chapter can be changed to<br />

emulate the Excel RAND() function by using the Volatile method, as follows:<br />

Function NONSTATICRAND()<br />

‘ Returns a random number that<br />

‘ changes when the sheet is recalculated<br />

Application.Volatile True<br />

NONSTATICRAND = Rnd<br />

End Function<br />

Using the False argument of the Volatile method causes the function to be recalculated<br />

only when one or more of its arguments change (if a function has no arguments, this method<br />

has no effect). By default, all functions work as if they include an Application.Volatile<br />

False statement.<br />

If you use this function, you’ll find that it is not recalculated when the worksheet is calculated. In<br />

other words, the function is not a volatile function. (For more information about controlling recalculation,<br />

see the nearby sidebar, “Controlling function recalculation.” You can make the function<br />

volatile by adding the following statement:<br />

Application.Volatile True<br />

After doing so, the DRAWONE function displays a new random cell value whenever the sheet is<br />

calculated.

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

Saved successfully!

Ooh no, something went wrong!