Handling Errors

When Word is asked to do something it can't do, an error condition occurs, and Word displays an error message box. An error condition is different from the WordBasic language errors described in the previous chapter; those errors are errors in the way a macro is written. However, a macro can be thoroughly debugged and still encounter error conditions. Here are some macro actions that can cause errors:

When you encounter these errors as you're working on documents in Word, you just close the error message box and continue working. But when a macro encounters an error, it stops, and the rest of the instructions in the macro are not carried out — unless you include instructions to trap, or handle, the error. When a macro handles an error, it can respond to it and continue. WordBasic includes several statements you can use to handle errors.

WordBasic and Word Errors

When you're working on documents in Word, the only errors you encounter are Word errors. A macro, however, can also generate WordBasic errors. Some WordBasic errors, such as syntax errors (discussed in the previous chapter), prevent a macro from running. Others — the ones you might want to trap — occur only when a macro is running in specific situations.

The distinction between WordBasic and Word errors is important because a macro can prevent a WordBasic error message box from being displayed, but cannot prevent a Word error message box from being displayed.

For example, if you run a macro that includes a command that is not available, WordBasic displays a WordBasic error message box, as shown in the following illustration. If you include instructions in your macro to handle that error, the error message box will not be displayed; the macro will carry out the error-handling instructions. The error-handling instructions could move the insertion point to a context in which the command is available, for example.

On the other hand, if a macro tries to move the insertion point to a bookmark that doesn't exist, Word generates a Word error and will display an error message box whether or not the macro includes error-handling instructions. The error-handling instructions do make a difference, however. Without them, Word stops the macro where the error occurs. With them, the macro can continue after the user closes the error message box, and the macro can respond to the error, perhaps by requesting the name of another bookmark.

Every error has a number. WordBasic errors have numbers below 1000; Word errors have numbers of 1000 or above. You can use these numbers in a macro to test for and respond to different types of errors. There are a few WordBasic errors, such as "Syntax error" and "Unknown Command, Subroutine, or Function," that prevent a macro from running and that you cannot trap.

For a complete list of WordBasic and Word error messages, see "Error Messages" in Part 2, "WordBasic Reference."

Error-Handling Instructions

WordBasic provides three forms of the On Error statement; the special variable Err; and the Error statement for handling errors in your macros.

On Error Goto Label

This form of the On Error statement enables error handling. It must be placed before the instruction that can generate an error. When an error occurs, Word goes to the line indicated by Label.

The following example displays an input box in which the user can type the name of a file to open. If the user chooses the Cancel button when the input box is displayed, a WordBasic error is generated. (You may not consider choosing the Cancel button an error, but WordBasic does.)

To trap the error, you place the On Error Goto Label instruction before the instruction that displays the input box. If the user chooses the Cancel button, the error is trapped, and Word goes to the line indicated by Label. In this case the label is bye, which is at the end of the macro. So if the user chooses the Cancel button in the input box, the macro ends without displaying an error message box.


Sub MAIN
On Error Goto bye
ans$ = InputBox$("Please type the name of a file to open:")
FileOpen ans$
'Series of instructions that operate on the file that was opened
bye:
End Sub

On Error Goto Label places the number of the error generated when the user chooses the Cancel button in the special variable Err, described later in this section.

On Error Resume Next

This form of the On Error statement allows a macro to trap errors and ignore them. When an error occurs, the macro simply resumes and goes to the next instruction as if nothing had happened. Using On Error Resume Next is sometimes the simplest way to deal with an error.

The following version of the previous example shows another way to deal with the error that occurs if the user chooses the Cancel button to close an input box. In this example, if the user chooses the Cancel button, the error is ignored. The If conditional tests whether a value was placed in the ans$ variable. No value is placed in it if the user chooses Cancel, so the FileOpen instruction doesn't run in that case.


Sub MAIN
On Error Resume Next
ans$ = InputBox$("Please type the name of a file to open:")
If ans$ <> "" Then FileOpen ans$
'Series of instructions that operate on the file that was opened
End Sub

After an On Error Resume Next instruction, Word continues to ignore any errors that might occur until the macro ends or until it encounters an instruction that disables error trapping, such as On Error Goto 0. As useful as it can be to have Word ignore specific errors, such as the one generated by the Cancel button, to have all errors ignored can cause problems: A macro may not work properly after an unexpected error occurs. So it's a good idea to disable error trapping (or use On Error Goto Label to reset error trapping) after using On Error Resume Next.

On Error Resume Next sets the value of the special variable Err to 0 (zero). Err is described later in this section.

On Error Goto 0

This form of the On Error statement is used to disable error trapping. While both On Error Goto Label and On Error Resume Next allow the macro to continue when an error occurs, On Error Goto 0 ensures that if an error is encountered, an error message is displayed and the macro stops.

You can use On Error Goto 0 to limit error handling to a specific part of your macro. In the following example, On Error Goto 0 is used to disable the error handling enabled by On Error Resume Next. Because the rest of the macro is meant to operate on an open file, the macro should end if no file is opened. On Error Goto 0 ensures that the macro is stopped if the FileOpen instruction generates an error.


Sub MAIN
On Error Resume Next
ans$ = InputBox$("Please type the name of a file to open:")
On Error Goto 0
If ans$ <> "" Then FileOpen ans$
'Series of instructions that operate on the file that was opened
End Sub

Err

When error trapping is enabled with On Error Goto Label, the number of any error that occurs is stored in the special variable Err. By testing this value, the macro can take different actions according to the type of error that occurs.

In the following example, the On Error Goto trap instruction enables error handling. The error-handling instructions, beginning after the label trap, test for three different values. If Err is equal to 102, it means that the user chose the Cancel button in the input box, in which case the Goto bye instruction ends the macro. If Err is equal to 1078 or 1177, the user typed either an invalid filename or the name of a file that isn't stored in the current folder. In either case, the macro displays a message box that asks the user if he or she would like to try to open the file again. If the user chooses the Yes button, the macro resets Err to 0 (zero) and goes to the tryagain label.

By default, Err has a value of 0 (zero). Once an error occurs and Err is assigned a nonzero value, error trapping is disabled until Err is reset to 0 (zero). In the following example, Err must be reset to 0 (zero) or error trapping will not work when the instructions after the tryagain label are repeated:


Sub MAIN
tryagain:
    On Error Goto trap
    ans$ = InputBox$("Please type the name of a file to open:")
    FileOpen ans$
    'Series of instructions that operate on the file that was opened
    Goto bye
trap:
    If Err = 102 Then Goto bye            'User cancels input box
    If Err = 1078 Or Err = 1177 Then        'Not found/invalid filename
        response = MsgBox("Couldn't open the file. Try again?", 4)
                If response = -1 Then
                Err = 0
                Goto tryagain
        End If
    End If
bye:
End Sub

You can look up the number that corresponds to any Word or WordBasic error message in "Error Messages" in Part 2, "WordBasic Reference."

Error

You can use the Error statement to generate an error so that you can test whether your error trap works as intended, without having to create an actual error situation. Here is an example:


On Error Goto trap
Error 502                'Simulate error 502
trap:
If Err = 502 Then MsgBox "Error was trapped."

If error trapping is not enabled before an Error instruction runs, Word highlights the Error instruction in the macro-editing window and stops the macro. If the error you specified is a WordBasic error, Word displays the corresponding error message box; if it is a Word error, no message is displayed.