VBA OnError异常处理无法正常工作

时间:2013-02-22 14:57:19

标签: excel vba excel-vba

我在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

2 个答案:

答案 0 :(得分:2)

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

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

答案 1 :(得分: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

可以重复这种方法来捕捉个别错误......