捕获和处理用户代码中的错误

在错误移动到标记代码并查看是否存在需要处理的特定错误。

Public Const cErrCodeNotNumber = 2262   ' This value must be a number.
Public Const cErrCodeNumericOverflow = 2263   ' The number is too large.

Private Sub MySub()
    Dim objConn As ADODB.Connection
    Dim objCmd As ADODB.Command
    Dim objRS As ADODB.Recordset
    'etc.

    On Error Goto ErrHandler
    [...My code goes here...]

ExitSub:
    'Cleanup
    If objConn.State <> adStateOpen Then objConn.Close 'Closing connection to database, if it is still open
    If Not objRS Is Nothing Then objRS.Close
    objConn = Nothing
    ObjRS = Nothing
    'Do any other cleaning.
    Exit Sub

ErrHandler:
    Select Case Err.Number
        Case cErrCodeNotNumber
            MsgBox "The value found is not a number. Execution stopped.", vbCritical
        Case cErrCodeNumericOverflow
            MsgBox "The value found is too big. [instructions how to resolve this]", vbCritical
        Case Else
            MsgBox "Error " & Err.Number & ". " & vbCrLf & Err.Source & "--->" & Err.Description, "Unrecoverable error", vbCritical
    End Select
    
    Goto ExitSub
End Sub