我有一本使用 VBA 的 Excel 书。当触发错误时,我尝试关闭整个 Excel 应用程序。但我发现 Excel session 仍在 Windows 任务管理器中运行。因此,我必须先终止 session ,然后才能正确重新启动应用程序并运行 VBA 程序。
如何处理错误,以便即使出现错误,我仍然可以运行 VBA 程序,而无需终止并重新启动 Excel 本身?
最佳答案
在子/函数的顶部写入
'ErrHandler is a label we put at the bottom of our code section.
On Error Goto ErrHandler
在函数/子的底部
Exit Function
ErrHandler:
'Do something here if there is an error
'For Example
Msgbox(Err.Description)
End Function
或
Exit Sub
ErrHandler:
'Do something here if there is an error
'For Example
Msgbox(Err.Description)
End Sub
注意一定要加上Exit语句,否则执行结束时会进入代码块
err 对象用于获取有关子/函数错误部分中的错误的信息。您可以使用它根据错误类型执行不同的操作。
例如。
Select Case err.Number
Case 13
Msgbox("Type Mismatch, macro will continue")
'Go back to the point of the error and resume code execution..
Resume Next
Case Else
Msgbox("A fatal error has occurred. Macro will end " & err.Description)
End Select
捕获特定错误代码的很好的引用。
关于vba - 为什么在 VBA 错误时必须从 Windows 任务管理器终止 Excel session ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15253238/