Access Common Error Handler
The VBA code illustrates a common error handler technique. Keep in mind there are three forms of the On Error Statement:
(1) On Error GoTo Line (Usually An Error Handling Routine)
(2) On Error GoTo 0 (Turns Off User Error Handling)
(3) On Error Resume Next (Ignores the Error And Executes The Next Statement
For a list of all error codes, see VBA Error Codes.
Program Code
' ************************************************** ' Module 1 - This Creates An Error Condition ' ************************************************** Option Compare Database Option Explicit Sub TestError() Dim intDividend As Integer Dim intDivisor As Integer Dim intResult As Integer On Error GoTo ErrorHandler intResult = intDividend / intDivisor Exit_Procedure: ' ********************************************* ' Close Files, Set Objects to Nothing ' ********************************************* DoCmd.SetWarnings True DoCmd.Hourglass False On Error GoTo 0 Exit Sub ErrorHandler: CommonErrorHandler Err.Number, Err.Description Resume Exit_Procedure End Sub ' ************************************************** ' Module 2 - This Displays The Error Message ' ************************************************** Option Compare Database Option Explicit Public Sub CommonErrorHandler(ErrorNumber As String, ErrorDescription As String) MsgBox "An Error Occurred In This Application" & vbCrLf & _ "Please Contact The Developer" & vbCrLf & vbCrLf & _ "Error Number = " & ErrorNumber & " Error Description = " & _ ErrorDescription, vbCritical End Sub ' ************************************************** ' Another Error Handler Technique from a Form ' ************************************************** Option Compare Database Option Explicit Private Sub cmdPurge_Click() ' ***************************************************************************** ' Sample Code: ' QueryDef To Selectively Delete Employers - The Parameter Value Will Come From ' The Listbox Items Selected By The User ' ***************************************************************************** Dim qd As DAO.QueryDef On Error GoTo ErrorHandler Set qd = CurrentDb.QueryDefs("qryPurge_tblEmployeesx") qd!prmEmployerID = 8 qd.Execute dbFailOnError Exit Sub ' ***************************************************************************** ' Handle Errors ' ***************************************************************************** ErrorHandler: HandleError Err.Number, Err.Description, "Purge Employers", Me.Name Err.Clear Resume Next End Sub Private Sub HandleError(intErr As Long, strErrorDescription As String, strFunction As String, strObject As String) On Error Resume Next MsgBox ("Error #------------------ " & intErr & vbCrLf & "Error Description-------- " & strErrorDescription & vbCrLf & _ "Processing Function---- " & strFunction & vbCrLf & "Error in Access Object-- " & strObject) End Sub