Error-Handling Techniques in Excel VBA

In This Chapter

Understanding the difference between programming errors and run-time errors
Trapping and handling run-time errors
Using the VBA On Error and Resume statements
Finding how you can use an error to your advantage
When working with VBA, you should be aware of two broad classes of errors: programming errors and run-time errors. (I cover programming errors, also known as bugs, in the next chapter.) A well-written program handles errors the way Fred Astaire danced: gracefully. Fortunately, VBA includes several tools to help you identify errors — and then handle them gracefully.

Types of Errors

If you’ve tried any of the examples in this topic, you have probably encountered one or more error messages. Some of these errors result from bad VBA code. For example, you may spell a keyword incorrectly or type a statement with the wrong syntax. If you make such an error, you won’t even be able to execute the procedure until you correct it.
This chapter does not deal with those types of errors. Instead, I discuss runtime errors — the errors that occur while Excel executes your VBA code. More specifically, this chapter covers the following:

Identifying errors

Doing something about the errors that occur Recovering from errors
Creating intentional errors (Yes, sometimes an error can be a good thing.)
The ultimate goal of error handling is to write code that avoids displaying Excel’s error messages as much as possible. In other words, you want to anticipate potential errors and deal with them before Excel has a chance to rear its ugly head with a (usually) less-than-informative error message.


An Erroneous Example

To get things started, I developed a short VBA macro. Activate the VBE, insert a module, and enter the following code:
tmp23-68
As shown in Figure 12-1, this procedure asks the user for a value. It then enters the square root of that value into the active cell.
The InputBox function displays a dialog box that asks the user for a value.
Figure 12-1:
The InputBox function displays a dialog box that asks the user for a value.
You can execute this procedure directly from the VBE by pressing F5. Alternatively, you may want to add a button to a worksheet (use the Forms toolbar to do this) and then assign the macro to the button. (Excel prompts you for the macro to assign.) Then you can run the procedure by simply clicking the button.

The macro’s not quite perfect

Enter this code and try it out. It works pretty well, doesn’t it? Now try entering a negative number when you are prompted for a value. Oops. Trying to
calculate the square root of a negative number is illegal on this planet. Excel responds with the message shown in Figure 12-2, indicating that your code generated a run-time error. For now, just click the End button. Or click the Debug button; Excel suspends the macro so you can use the debugging tools. (I describe the debugging tools in Chapter 13.)
Excel displays this error message when the procedure attempts to calculate the square root of a negative number.
Figure 12-2:
Excel displays this error message when the procedure attempts to calculate the square root of a negative number.
Most folks don’t find the Excel error messages (for example, Invalid procedure call or argument) very helpful. To improve the procedure, you need to anticipate this error and handle it more gracefully.

Here’s a modified version of Enter Square Root:

tmp23-71
An If-Then structure checks the value contained in the Num variable. If Num is less than 0, the procedure displays a message box containing information that humans can actually understand. The procedure ends with the Exit Sub statement, so the error never has a chance to occur.

The macro is still not perfect

So the modified Enter Square Root procedure is perfect, right? Not really. Try entering text instead of a value. Or click the Cancel button in the input box. Both of these actions generate an error (Type mismatch).
The following modified code uses the IsNumeric function to make sure that Num contains a numeric value. If the user doesn’t enter a number, the procedure displays a message and then stops. Also, notice that the Num variable is now defined as a Variant. If it were defined as a Double, the code would generate an unhandled error if the user entered a nonnumeric value into the input box.
tmp23-72

Is the macro perfect yet?

Now this code is absolutely perfect, right? Not quite. Try running the procedure while the active sheet is a Chart sheet. As shown in Figure 12-3, Excel displays another message that’s as illuminating as the other error messages you’ve seen. This error occurs because there is no active cell on a Chart sheet.
Running the procedure when a chart is selected=
Figure 12-3:
Running the procedure when a chart is selected generates this error.
The following listing uses the Type Name function to make sure the selection is a range. If anything other than a range is selected, this procedure displays a message and then exits:
tmp23-74

Giving up on perfection

By now, this procedure simply must be perfect. Think again, pal. Protect the worksheet (using the Tools Protection Protect Sheet command) and then run the code. Yep, a protected worksheet generates yet another error. And I probably haven’t thought of all the other errors that can occur. Keep reading for another way to deal with errors — even those you can’t anticipate.

Handling Errors Another Way

How can you identify and handle every possible error? The answer is that often you can’t. Fortunately, VBA provides another way to deal with errors.

Revisiting the Enter Square Root procedure

Examine the following code. I modified the routine from the previous section by adding an On Error statement to trap all errors and then checking to see whether the InputBox was cancelled.
tmp23-75

On Error not working?

If an On Error statement isn’t working as advertised, you need to change one of your settings.
1. Activate the VBE.
2. Choose the Tools Options command.
3. Click the General tab of the Options dialog box.
4. Make sure that the Break On All Errors setting is deselected.
If this setting is selected, Excel essentially ignores any On Error statements. You normally want to keep the Error Trapping options set to Break on Unhandled Errors.
This routine traps any type of run-time error. After trapping a run-time error, the revised EnterSquareRoot procedure displays the message box shown in Figure 12-4.
A run-time error in the procedure generates this helpful error message.
Figure 12-4:
A run-time error in the procedure generates this helpful error message.

About the On Error statement

Using an On Error statement in your VBA code causes Excel to bypass its built-in error handling and use your own error-handling code. In the previous example, a run-time error causes macro execution to jump to the statement labeled Bad Entry. As a result, you avoid Excel’s unfriendly error messages and you can display your own (friendlier, I hope) message to the user.
Notice that the example uses an Exit Sub statement right before the BadEntry label. This statement is necessary because you don’t want to execute the error-handling code if an error does not occur.

Handling Errors: The Details

You can use the On Error statement in three ways, as shown in Table 12-1.

Table 12-1 Using the On Error Statement
Syntax What It Does
On Error After executing this statement, VBA resumes GoTo label
execution at the specified line. You must include a colon
after the label so that VBA recognizes it as a label.
On Error Resume Next After executing this statement, VBA simply ignores all
errors and resumes execution with the next statement.
On Error GoTo 0 After executing this statement, VBA resumes its normal
error-checking behavior. Use this statement after using
one of the other On Error statements or when you want to
remove error handling in your procedure.

Resuming after an error

In some cases, you simply want your routine to end gracefully when an error occurs. For example, you may display a message describing the error and then exit the procedure. (The EnterSquareRoot5 example uses this technique.) In other cases, you want to recover from the error, if possible.
To recover from an error, you must use a Resume statement. This clears the error condition and lets you continue execution at some location. You can use the Resume statement in three ways, as shown in Table 12-2.

Table 12-2 Using the Resume Statement
Syntax What It Does
Resume Execution resumes with the statement that caused the
error. Use this if your error-handling code corrects the
problem and it’s okay to continue.
Resume Next Execution resumes with the statement immediately follow-
ing the statement that caused the error. This essentially
ignores the error.
Resume label Execution resumes at the label you specify.

The following example uses a Resume statement after an error occurs:

tmp23-77
This procedure has another label: TryAgain. If an error occurs, execution continues at the BadEntry label and the code displays the message shown in Figure 12-5. If the user responds by clicking Yes, the Resume statement kicks in and execution jumps back to the TryAgain label. If the user clicks No, the procedure ends.
If an error occurs, the user can decide whether to try again.
Figure 12-5:
If an error occurs, the user can decide whether to try again.
Remember that the Resume statement clears the error condition before continuing. To see what I mean, try substituting the following statement for the second-to-last statement in the preceding example:
tmp23-79
The code, which is available on this topic’s Web site, doesn’t work correctly if you use GoTo instead of Resume. To demonstrate, enter a negative number: You get the error prompt. Click Yes to try again and then enter another negative number. This second error is not trapped because the original error condition was not cleared.

Error handling in a nutshell

To help you keep all this error-handling business straight, I’ve prepared a quick-and-dirty summary. An error-handling routine has the following characteristics:
It begins immediately after the label specified in the On Error statement.
It should be reached by your macro only if an error occurs. This means that you must use a statement such as Exit Sub or Exit Function immediately before the label.
It may require a Resume statement. If you choose not to abort the procedure when an error occurs, you must execute a Resume statement before returning to the main code.

Knowing when to ignore errors

In some cases, it’s perfectly okay to ignore errors. That’s when the On Error Resume Next statement comes into play.
The following example loops through each cell in the selected range and converts the value to its square root. This procedure generates an error message if any cell in the selection contains a nonpositive number:
tmp23-80
In this case, you may want to simply skip any cell that contains a value you can’t convert to a square root. You could create all sorts of error-checking capabilities by using If-Then structures, but you can devise a better (and simpler) solution by simply ignoring the errors that occur.

The following routine accomplishes this by using the On Error Resume Next statement:

tmp23-81
In general, you can use an On Error Resume Next statement if you consider the errors inconsequential to your task.

Identifying specific errors

All errors are not created equal. Some are serious and some are less serious. Although you may ignore errors you consider inconsequential, you must deal with other, more serious errors. In some cases, you need to identify the specific error that occurred.
When an error occurs, Excel stores the error number in an Error object named Err. This object’s Number property contains the error number. You can get a description of the error by using the VBA Error function. For example, the following statement displays the error number and a description:
tmp23-82
Figure 12-6 shows an example of this. Keep in mind, however, that the Excel error messages are not always very useful — but you already know that.
Displaying an error number and a description.
Figure 12-6:
Displaying an error number and a description.
The following procedure demonstrates how to determine which error occurred. In this case, you can safely ignore errors caused by trying to get the square root of a nonpositive number (that is, error 5) or errors caused by trying to get the square root of a nonnumeric value (error 13). On the other hand, you need to inform the user if the worksheet is protected and the selection contains one or more locked cells. (Otherwise, the user may think the macro worked when it really didn’t.) This event causes error 1004.
tmp23-84
When a run-time error occurs, execution jumps to the ErrorHandler label. The Select Case structure tests for three common error numbers. If the error number is 5 or 13, execution resumes at the next statement. (In other words, the error is ignored.) But if the error number is 1004, the routine advises the user and then ends. The last case, a catch-all for unanticipated errors, traps all other errors and displays the actual error message.

An Intentional Error

Sometimes you can use an error to your advantage. For example, suppose you have a macro that works only if a particular workbook is open. How can you determine whether that workbook is open? Perhaps the best solution is to write a general-purpose function that accepts one argument (a workbook name) and returns True if the workbook is open, False if it’s not.

Here’s the function:

tmp23-85
This function takes advantage of the fact that Excel generates an error if you refer to a workbook that is not open. For example, the following statement generates an error if a workbook named MyBook.xls is not open:
tmp23-86
In the Workbook Open function, the On Error statement tells VBA to resume the macro at the NotOpen statement if an error occurs. Therefore, an error means the workbook is not open, and the function returns False. If the workbook is open, no error occurs and the function returns True.
Here’s another variation on the Workbook Open function. This version uses On Error Resume Next to ignore the error. But the code checks Err’s Number property. If Err.Number is 0, no error occurred and the workbook is open. If Err.Number is anything else, it means that an error occurred (and the workbook is not open).
tmp23-87

The following example demonstrates how to use this function in a Sub procedure:

tmp23-88
The Macro1 procedure (which must be in the same project as Workbook Open) calls the Workbook Open function and passes the workbook name (Prices.xls) as an argument. The Workbook Open function returns either True or False. Therefore, if the workbook is not open, the procedure informs the user of that fact. If the workbook is open, the macro continues.
Error handling can be a tricky proposition — after all, many different errors can occur and you can’t anticipate them all. In general, you should trap errors and correct the situation before Excel intervenes, if possible. Writing effective error-trapping code requires a thorough knowledge of Excel and a clear understanding of how the VBA error handling works. Subsequent chapters contain more examples of error handling.

Next post:

Previous post: