Error Object, Errors Collection Example (MDB)

The following example generates an error by attempting to open a Recordset object on a nonexistent Students table. Information about the error is stored in both the DAO Error object and the Visual Basic Err object. The procedure prints the value of the Description, Source, and Number properties of the Error object. Then it prints the values of the corresponding properties of the Err object.

Note that the last Error object in the Errors collection should always refer to the same error as the Err object. That is, the value of Err.Number should be equivalent to Errors.Count – 1. If these two values aren't equivalent, information in the Errors collection may be outdated. Use the Refresh method to ensure that the Errors collection includes the most recent error information.

Sub CheckError()
    Dim dbs As Database, tdf As TableDef, rst As Recordset
    ' Declare Error object variable for enumeration
    ' of Errors collection.
    Dim errX As Error
    
    ' Ignore errors.
    On Error Resume Next
    ' Clear error in Err object.
    Err.Clear
    ' Refresh Errors collection.
    Errors.Refresh
    ' Return reference to current database.
    Set dbs = CurrentDb
    ' Attempt to open Recordset object on nonexistent table.
    Set rst = dbs.OpenRecordset("Students")
    Debug.Print "DAO Error Object:"
    ' Print number of errors in Errors collection.
    Debug.Print ">>>Number of errors: "; Errors.Count
    ' Enumerate Errors collection and key properties.
    For Each errX In DBEngine.Errors
        Debug.Print errX.Description
        Debug.Print errX.Source
        Debug.Print errX.Number
    Next errX
    Debug.Print
    Debug.Print "VBA Err Object:"
    ' Display corresponding properties of Err object.
    Debug.Print Err.Description
    Debug.Print Err.Source
    Debug.Print Err.Number
    Set dbs = Nothing
End Sub