【问题标题】:VBA On Error statement executes without errorVBA On Error 语句执行没有错误
【发布时间】:2026-01-28 21:15:02
【问题描述】:

我正在使用下面的简单代码来处理错误。当没有错误时为什么会出现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

【问题讨论】:

  • 在 ErrHandler 之前添加一个 Exit Sub,这样函数就可以终止了。

标签: excel error-handling vba


【解决方案1】:

您应该在实际错误处理程序之前添加一个出口,并在显示对话框后恢复默认错误处理。 (第一个错误转到 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

【讨论】:

    最近更新 更多