Microsoft Office Tutorials and References
In Depth Information
In this line of code, line label specifies the section of code you have written to handle errors.
The following code fragment shows how you could trap errors and branch to a label named
ErrorHandler :
On Error GoTo ErrorHandler
[error handler statements]
Because you would want to start trapping errors as quickly as possible, the On Error state­
ment should be at the beginning of the procedure. Also, you are not limited to only a single
error handler per procedure; you could specify different error handlers as the procedure
progresses, even returning to earlier error handlers. The following code fragment illustrates
one way to construct a series of error- handling routines:
On Error GoTo ErrorHandler1
On Error GoTo ErrorHandler2
On Error GoTo ErrorHandler1
[errorhandler1 statements]
[errorhandler2 statements]
Because VBA will execute an entire procedure until the end is reached, it is necessary to
include instructions so that VBA will skip any error handlers you have written if no error has
been trapped. The most common way to cause VBA to avoid executing error-handling code
is to place all error-handling code at the end of a procedure and then, in the line immediately
before the error handler, placing the Exit Sub or Exit Function statement to exit the procedure.
For more information about the two types of procedures (Sub procedures and Function procedures), see
Chapter 5, “Creating Sub and Function Procedures.”
Once an error has been trapped, how can you tell what the error was and take corrective
actions if possible? VBA sets various properties of the Err object to describe the error. Two of
the properties, Number and Description , provide a numerical error code and a string descrip­
tion, respectively, of the error. You can use the error code to recognize and correct common
or expected errors.
Error handlers work only for the procedure in which they appear; once the procedure has
ended, the error trap is disabled. You can also disable the error handler yourself by using the
following statement:
On Error GoTo 0
Search JabSto ::

Custom Search