1

我的 VBA 中有以下示例代码。每当我遇到与系统相关的错误时,我想显示我自己的错误消息。但是下面的代码不起作用。

VBA 告诉

类型不匹配

我想

您好,您的日期无效

我的代码

Sub good()

Dim date_ As Date
date_ = "hello"

On Error GoTo Err1:

Err1:
    MsgBox "Hello your date is invalid"
    ' more code

End Sub
4

2 回答 2

2

您需要在发生错误之前On Error放置语句,通常在过程的最开始。将该语句视为一个指令,它告诉 VBA 如何处理过程中稍后遇到的任何错误。On Error

Sub good()

On Error GoTo Err1

Dim date_ As Date
date_ = "hello"

Exit Sub 'Make sure you include this so successful executions 
         'don't continue into the error block.

Err1:
    Select Case Err.Number
      Case 101 'Not the actual error number!
         MsgBox "Hello your date is invalid"
      Case 102 'Not the actual error number!
         MsgBox "Something else bad happened!"
      Case Else
         MsgBox "I don't know what happened - unexpected error!"
    End Select
    ' more code

End Sub
于 2013-02-22T14:59:30.357 回答
2

您需要将On Error语句放在错误之前!

另外,不要忘记Exit Sub最后的,否则您的例程将始终运行错误代码:

Sub good()
    Dim date_ As Date

    On Error GoTo Err1:
    date_ = "hello"

    On Error Goto 0 'goes back to default, i.e. show debugger
    Exit Sub

Err1:
    MsgBox "Hello your date is invalid"
    ' more code

End Sub

或者,您可以这样做

Sub good()
    Dim date_ As Date

    On Error Resume Next
    date_ = "hello"
    If Err.Number <> 0 Then
        MsgBox "Wrong type"
        Err.Clear
        Exit Sub
    End If

    On Error Goto 0

    ' more code

End Sub

可以重复此方法以捕获单个错误...

于 2013-02-22T15:01:27.050 回答