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 703<br />

First, change the argument from a String data type to a Variant. If the argument’s data type<br />

is String, Excel tries to convert whatever it gets (for example, number, Boolean value) to a<br />

String and usually succeeds. Next, the Excel ISNONTEXT function is used to determine whether<br />

the argument is not a text string. If the argument is not a text string, the function returns the<br />

#N/A error. Otherwise, it returns the characters in reverse order.<br />

The data type for the return value of the original REVERSETEXT function was String<br />

because the function always returned a text string. In this revised version, the function<br />

is declared as a Variant because it can now return something other than a string.<br />

Returning an array from a function<br />

Most functions that you develop with VBA return a single value. It’s possible, however, to write a<br />

function that returns multiple values in an array.<br />

Part IV deals with arrays and array formulas. Specifically, these chapters provide examples<br />

of a single formula that returns multiple values in separate cells. As you’ll see, you<br />

can also create custom functions that return arrays.<br />

VBA includes a useful function called Array. The Array function returns a variant that contains<br />

an array. It’s important to understand that the array returned is not the same as a normal array<br />

composed of elements of the variant type. In other words, a variant array is not the same as an<br />

array of variants.<br />

If you’re familiar with using array formulas in Excel, you have a head start understanding the VBA<br />

Array function. You enter an array formula into a cell by pressing Ctrl+Shift+Enter. Excel inserts<br />

brackets around the formula to indicate that it’s an array formula. See Chapter 15 for more details<br />

on array formulas.<br />

The lower bound of an array created by using the Array function is, by default, 0.<br />

However, the lower bound can be changed if you use an Option Base statement.<br />

The following MONTHNAMES function demonstrates how to return an array from a Function<br />

procedure:<br />

Function MONTHNAMES() As Variant<br />

MONTHNAMES = Array( _<br />

“Jan”, “Feb”, “Mar”, “Apr”, _<br />

“May”, “Jun”, “Jul”, “Aug”, _<br />

“Sep”, “Oct”, “Nov”, “Dec”)<br />

End Function

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

Saved successfully!

Ooh no, something went wrong!