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.

624<br />

Part VI: Developing Custom Worksheet Functions<br />

This function returns an element from a delimited text string, and uses three arguments. For<br />

example, the following formula returns the string fghi (the third element in the string, which uses<br />

a dash to separate the elements):<br />

=EXTRACTELEMENT(“ab-cde-fghi-jkl”, 3 “-”)<br />

Following is a VBA Sub procedure that adds argument descriptions, which appear in the<br />

Function Arguments dialog box:<br />

Sub DescribeFunction()<br />

Dim desc(1 To 3) As String<br />

desc(1) = “The delimited text string”<br />

desc(2) = “The number of the element to extract”<br />

desc(3) = “The delimiter character”<br />

Application.MacroOptions Macro:=”EXTRACTELEMENT”,<br />

ArgumentDescriptions:=desc<br />

End Sub<br />

The argument descriptions are stored in an array, and that array is used as the ArgumentDescriptions<br />

argument for the MacroOptions method. You need to run this procedure only one time. After<br />

doing so, the argument descriptions are stored in the workbook.<br />

Testing and Debugging Your Functions<br />

Naturally, testing and debugging your custom function is an important step that you must take to<br />

ensure that it carries out the calculation that you intend. This section describes some debugging<br />

techniques that you may find helpful.<br />

If you’re new to programming, the information in this section will make a lot more<br />

sense after you’re familiar with the material in Chapter 24.<br />

VBA code that you write can contain three general types of errors:<br />

Syntax errors: An error in writing the statement — for example, a misspelled keyword, a<br />

missing operator, or mismatched parentheses. The VB Editor lets you know about syntax<br />

errors by displaying a pop-up error box. You can’t use the function until you correct all<br />

syntax errors.<br />

Runtime errors: Errors that occur as the function executes. For example, attempting to<br />

perform a mathematical operation on a string variable generates a runtime error. Unless<br />

you spot it beforehand, you won’t be aware of a runtime error until it occurs.<br />

Logical errors: Code that runs but simply returns the wrong result.

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

Saved successfully!

Ooh no, something went wrong!