VBA OnError异常处理不起作用
我在我的VBA中有以下示例代码。每当我面对系统相关的错误,我想显示我自己的错误消息。但下面的代码不起作用。VBA OnError异常处理不起作用
VBA告诉
类型不匹配
我想
你好你的日期是无效的
我的代码
Sub good()
Dim date_ As Date
date_ = "hello"
On Error GoTo Err1:
Err1:
MsgBox "Hello your date is invalid"
' more code
End Sub
您需要在之前将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
您需要将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
这种方法可以重复捕捉个人错误...
如果我有2个不同的数据类型,并且如果我想提出不同的异常,我是否需要在每个数据类型上单独编写OnError? – logan 2013-02-22 15:07:52
@logan:查看我更新的答案 – 2013-02-22 16:02:08
谢谢..工作正常.. 但是,如果我不知道错误发生在哪里? – logan 2013-02-22 15:00:52
您不需要知道发生错误的位置。将过程结束时的所有错误处理置于单独的错误处理块中。 – 2013-02-22 15:02:27
@Logan:这就是为什么你把错误语句放在任何你希望发生错误的地方之前,也就是说,在你最好的情况下...... – 2013-02-22 15:02:32