Show Contents / Index / Search

Trapping Runtime Errors

The first step in dealing with runtime errors is to set a "trap" to catch the error. You do this by including an On Error statement in your macro. When a runtime error occurs, the On Error statement transfers control to an error-handling routine. (Refer to the On Error statement topic in the Visual Basic Help for more information.)

To trap errors correctly, you must set your error trap above the point in the procedure where errors are likely to occur. In general, this means that your error trap should be placed near the top of the procedure. Further, to avoid having the error-handling routine execute even when no error occurs, you should include an Exit Sub or Exit Function statement just before the error-handling routine's label.

Each of the following examples show the general structure of a procedure that includes an error trap and error-handling routine.

Examples of Error Trapping