使用VBA为特定的Excel错误消息制作消息?

时间:2012-07-16 14:22:55

标签: excel vba excel-vba

有没有办法说错误1004出现,显示消息“消息”和如果错误9,显示消息“消息2”而不是通用非描述符极客说话消息给最终用户?

1 个答案:

答案 0 :(得分:6)

您要做的是称为错误处理。

参见此示例。您可以使用Err.Number

来捕获错误号
Sub Sample()
    On Error GoTo Whoa

    '~~> Rest of the code

    Exit Sub
Whoa:
    Select Case Err.Number
        Case 9
            MsgBox "Message1"
        Case 1004
            MsgBox "Message2"
    End Select
End Sub

<强>后续

Sub Sample1()
    On Error GoTo Whoa

    '~~> Rest of the code

    Exit Sub
Whoa:
    MsgBox GetErrMsg(Err.Number)
End Sub

Sub Sample2()
    On Error GoTo Whoa

    '~~> Rest of the code

    Exit Sub
Whoa:
    MsgBox GetErrMsg(Err.Number)
End Sub

Function GetErrMsg(ErNo As Long) As String
    Select Case ErNo
        Case 9
            GetErrMsg = "Message1"
        Case 1004
            GetErrMsg = "Message2"
        Case Else
            GetErrMsg = "Message3"
    End Select
End Function