VBA OnErrorexception处理不起作用

我有以下示例代码在我的VBA。 每当我面对系统相关的错误,我想显示我自己的错误信息。 但是下面的代码不起作用。

VBA告诉

types不匹配

我想要

你好,你的date是无效的

我的代码

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语句。 将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之前放置On Error语句!

此外,不要忘记在最后的Exit Sub ,否则你的例程将总是运行错误代码:

 Sub good() Dim date_ As Date On Error GoTo Err1: date_ = "hello" On Error Goto 0 'goes back to default, ie 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 

这种方法可以重复捕捉个人错误…