2

我有一本带有 VBA 的 excel 书。触发错误时,我会尝试关闭整个 Excel 应用程序。但我发现 Excel 会话仍在 Windows 任务管理器中运行。因此,我必须先终止会话,然后才能正确重新启动应用程序并运行 VBA 程序。

如何处理错误,以便即使出现错误,我仍然可以运行 VBA 程序,而无需终止并重新启动 Excel 本身?

4

2 回答 2

2

在您的子/功能顶部写

'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

捕获特定错误代码的好参考。

http://www.mcoffice.com/faq/edi/errors.html

于 2013-03-06T17:44:14.810 回答
1

如果您通过以下几行赋予用户对应用程序的控制权

xlApp.Visible = True
xlApp.UserControl = True

它不会消失,否则End子或函数应该释放错误的进程

于 2013-03-06T18:39:53.860 回答