Professional Excel Development [Electronic resources] : The Definitive Guide to Developing Applications Using Microsoft® Excel and VBA®

Stephen Bullen, Rob Bovey, John Green

نسخه متنی -صفحه : 225/ 100
نمايش فراداده

Simple Error Handling

In the simplest form of error handling, error handlers are placed only in entry point procedures. Entry point procedures are those procedures from which code execution can be initiated. They are typically the procedures assigned to menu items, toolbar buttons, or controls placed on worksheets, but most event procedures are also entry points, because they initiate execution based on some action made by the user.

If the error handler in an entry point procedure is the only error handler in its call stack, this error handler will trap all errors that occur in all lower-level procedures. A simple error handler will display an error message to the user and exit the procedure. An example of this is shown in Listing 12-5.

Listing 12-5. An Example of a Simple Error Handler

Public Sub MyEntryPoint()
On Error GoTo ErrorHandler
' Your code here.
ErrorExit:
Exit Sub
ErrorHandler:
MsgBox Err.Description, vbCritical, "Application Name"
Resume ErrorExit
End Sub

Simple error handlers are appropriate only for the most trivial applications. An example might be a utility add-in that provides a number of simple features that require a small amount of code and do not require any significant cleanup. The primary purpose of a simple error handler is to shield users from raw runtime errors such as the one shown in Figure 12-1.