vba - 为什么在 VBA 错误时必须从 Windows 任务管理器终止 Excel session

标签 vba excel

我有一本使用 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

捕获特定错误代码的很好的引用。

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

关于vba - 为什么在 VBA 错误时必须从 Windows 任务管理器终止 Excel session ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15253238/

相关文章:

vba - Excel VBA 导入 .txt 文件导致日期格式错误

vba - Excel VBA 中的循环单词匹配函数

vba - 将数字添加到文本时出错

vba - 使用案例在单元格更改上运行宏

excel - 如何使用 open xml C# 禁用 Excel 中的网格线?

mysql - Excel VBA SQL 连接语法错误

vba - 从 csv 导入到 ms Access 表

excel - 减少重复代码以避免 "Procedure Too Large"错误

vba - 通过 vba 启用自动另存为(无需在提示时单击“保存”)

excel - 如何在 laravel excel 版本 3 中添加列的标题和总和值?