Microsoft Access 2010 Bible

(Rick Simeone) #1

Part III: More-Advanced Access Techniques


838


‘Insert your code here
ExitHere:
Exit Sub
HandleError:
If cnn.Errors.Count > 0 Then
If Err.Number = cnn.Errors.Item(0).Number Then
‘Error is an ADO Connection Error:
For Each errX In cnn.Errors
‘Loop through the Errors collection, displaying
‘the description of each Err object:
strMessage = strMessage & Err.Description & vbCrLf
Next errX
MsgBox strMessage, , “ADO Error Handler”
End If
Resume ExitHere
Else
‘The error is a VBA Error:
MsgBox Err.Description, vbExclamation, _
“VBA Error Handler”
Resume ExitHere
End If
End Sub

Summary


This chapter surveys the important topic of adding error handling in Access applications. All VBA
hosts (Access, Word, Excel, and so on) use identical error-handling paradigms. This means that all
the code you saw in this chapter is applicable to any VBA host application.

Error handling is enabled with the On Error keywords. The typical error-handling process is to
trap the error, redirect program execution to the code segment handling the error, and then
resume out of the error handler. Most procedures use the Resume statement to redirect program
flow to a common exit point in the procedure. The code following the exit label performs any
cleanup (closing and discarding object variables, closing files that are open, and so on) and is exe-
cuted regardless of whether an error occurs in the procedure.
Free download pdf