Microsoft Access 2010 Bible

(Rick Simeone) #1

Part III: More-Advanced Access Techniques


830


Msgbox Err.Description
Resume ExitHere
End Function

The On Error statement enables the error handler. In the event that an error occurs, execution
branches to the first line after the HandleError label. This label could be any valid VBA label.
The error-handler code would deal with the error and then either resume execution back in the
body of the procedure or just exit the function or subroutine. The inclusion of the MsgBox state-
ment in the error handler is a common way of informing the user what happened.

When an error occurs in a called function or a subroutine that doesn’t have an enabled error han-
dler, VBA returns to the calling procedure looking for an error handler. This process proceeds up
the call stack until a procedure with an error handler is found. What this means is that an error
thrown from a subordinate procedure may be handled by a higher-level procedure, making it diffi-
cult to know exactly which procedure triggered the error.

If no error handler is found, execution stops with the default Access error message displayed.

On Error GoTo Label
The On Error GoTo Label statement defines an error-handling code segment. On Error GoTo
Label (such as On Error GoTo HandleError) is the standard error-handling directive described
earlier in this chapter. Here is another example of using On Error GoTo Label within a VBA
procedure:

Sub LogMoreErrors()
Dim db As DAO.Database
Dim rs As DAO.Recordset
On Error GoTo HandleError
Set db = CurrentDb()
Set rs = db.OpenRecordset(“SELECT * FROM ErrorLog”)
‘Put code here to use the information
‘retrieved from the ErrorLog table.
ExitHere:
rs.Close
Exit Sub
HandleError:
MsgBox Err.Number & “ “ & Err.Description
Resume ExitHere
End Sub

On Error GoTo Label is, by far, the most common error trap you’ll add to your VBA procedures.
Because the GoTo statement defines an unconditional branch to the location specified by the Label
clause, you’re guaranteed that errors within the procedure will be handled by the error handler
you’ve written.

Keep in mind that you’re free to use any labels you wish as the targets of the On Error and
Resume statements, as long as those labels actually exist in your procedure. The labels you see
Free download pdf