VBA On Error语句执行时没有错误

时间:2014-06-04 12:45:54

标签: excel-vba error-handling vba excel

我使用下面的简单代码来处理错误。当msgbox出现原因时没有错误?如何在出现错误时才显示msgbox?

Sub Test()
On Error GoTo ErrHandler
On Error GoTo 0


'rest of the code is here

ErrHandler:
MsgBox "Please make sure the file exists in the current folder."
Exit Sub
End Sub

1 个答案:

答案 0 :(得分:4)

您应该在实际的错误处理程序之前添加一个出口,并在显示该对话框后恢复默认的错误处理。 (错误转到0的第一个可能是错位的)。

Sub Test()
On Error GoTo ErrHandler


'rest of the code is here

'Exit before error handlers
Exit Sub

ErrHandler:
  MsgBox "Please make sure the file exists in the current folder."
  ' Reset error handler
  On Error GoTo 0
  Exit Sub
End Sub