Part III: More-Advanced Access Techniques
828
The Err object also has two methods: Clear, to clear information from the Err object, and
Raise, to force an error condition. The Raise method is often used to test error handlers to
make sure they’re catching specific errors.
The Description property returns the built-in description of the error that has occurred. The
description is the same as the message displayed in the default error dialog box (such as Type
mismatch — refer to Figure 23.2). Whether you choose to use this description is entirely up to
you. Perhaps the most important property of the Err object is the Number associated with the
error. The following listing shows how you might use the Err.Number property to determine
which error has triggered the error handler:
Sub GenericProcedure()
On Error GoTo HandleError
‘Other VBA statements here
ExitHere:
‘Shut down statements here
Exit Sub
HandleError:
Select Case Err.Number
Case 123
‘Handle error number 123
Resume ExitHere
Case 456
‘Handle error number 456
Resume ExitHere
Case 789
‘Handle error number 789
Resume ExitHere
Case Else ‘Unanticipated error
MsgBox Err.Number & “ “ & Err.Description
Resume ExitHere
End Select
End Sub
The Select Case statement in the error handler uses Err.Number to execute any of a number
of responses to the error. The beauty of Select Case is that the error-handling code can be
extended as far as necessary. There is no practical limit on the number of Case statements that can
be contained within the Select Case construct, and multiple Err.Number values can be han-
dled by a single Case statement.
In each Case construct, you choose whether to include the Resume ExitHere statement. For
instance, perhaps Case 456 fixes the problem, and you really want the code to return to the state-
ment that caused the error so that it can be executed a second time. In this case, rather than
Resume ExitHere, use a simple Resume statement with no target label. Resume instructs VBA
to go back to the statement that caused the problem and execute it again. (The different forms of
the Resume statement are discussed in the “VBA Resume statements” section, later in this chapter.)