CodeContextObject Property Example

In the following example the CodeContextObject property is used in a function to identify the name of the object in which an error occurred. The object name is then used in the message box title as well as in the body of the error message. The Error statement is used in the command button's click event to generate the error for this example.

Private Sub Command1_Click()
    On Error GoTo Command1_Err
    Error 11                    ' Generate divide-by-zero error.
    Exit Sub

    Command1_Err:
        If ErrorMessage("Command1_Click() Event", vbYesNo + _
                vbInformation, Err) = vbYes Then
            Exit Sub
        Else
            Resume
        End If
End Sub

Function ErrorMessage(strText As String, intType As Integer, _
        intErrVal As Integer) As Integer
    Dim objCurrent As Object
    Dim strMsgboxTitle As String
    Set objCurrent = CodeContextObject
    strMsgboxTitle = "Error in " & objCurrent.Name
    strText = strText & "Error #" & intErrVal _
        & " occured in " & objCurrent.Name
    ErrorMessage = MsgBox(strText, intType, strMsgboxTitle)
    Err = 0
End Function