11.08.2013 Views

Excel's Formula - sisman

Excel's Formula - sisman

Excel's Formula - sisman

SHOW MORE
SHOW LESS

Create successful ePaper yourself

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

Chapter 23: Function Procedure Basics 625<br />

To force the code in a VBA module to be checked for syntax errors, choose Debug➜<br />

Compile xxx (where xxx is the name of your project). Executing this command highlights<br />

the first syntax error, if any exists. Correct the error and issue the command again<br />

until you find all of the errors.<br />

An error in code is sometimes called a bug. The process of locating and correcting such an error<br />

is debugging.<br />

When you test a Function procedure by using a formula in a worksheet, runtime errors can be<br />

difficult to locate because (unlike syntax errors) they don’t appear in a pop-up error box. If a runtime<br />

error occurs, the formula that uses the function simply returns an error value (#VALUE!).<br />

This section describes several approaches to debugging custom functions.<br />

While you’re testing and debugging a custom function, it’s a good idea to use the<br />

function in only one formula in the worksheet. If you use the function in more than one<br />

formula, the code is executed for each formula, which will get annoying very quickly!<br />

Using the VBA MsgBox statement<br />

The MsgBox statement, when used in your VBA code, displays a pop-up dialog box. You can use<br />

MsgBox statements at strategic locations within your code to monitor the value of specific variables.<br />

The following example is a Function procedure that should reverse a text string passed as<br />

its argument. For example, passing Hello as the argument should return olleH. If you try to use<br />

this function in a formula, however, you will see that it does not work — it contains a logical error:<br />

Function REVERSETEXT(text) As String<br />

‘ Returns its argument, reversed<br />

Dim TextLen As Long, i As Long<br />

TextLen = Len(text)<br />

For i = TextLen To 1 Step -1<br />

REVERSETEXT = Mid(text, i, 1) & REVERSETEXT<br />

Next i<br />

End Function<br />

You can insert a temporary MsgBox statement to help you figure out the source of the problem.<br />

Here’s the function again, with the MsgBox statement inserted within the loop:<br />

Function REVERSETEXT(text) As String<br />

‘ Returns its argument, reversed<br />

Dim TextLen As Long, i As Long<br />

TextLen = Len(text)<br />

For i = TextLen To 1 Step -1<br />

REVERSETEXT = Mid(text, i, 1) & REVERSETEXT<br />

MsgBox REVERSETEXT<br />

Next i<br />

End Function

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

Saved successfully!

Ooh no, something went wrong!