【问题标题】:why Excel session has to be killed from Windows Task Manager on VBA error为什么必须在 VBA 错误时从 Windows 任务管理器中终止 Excel 会话
【发布时间】:2013-03-06 16:49:19
【问题描述】:

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

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

【问题讨论】:

  • 请向我们展示您的代码
  • 如果您打开隐藏的工作簿或其他情况,可能会发生这种情况。

标签: vba excel


【解决方案1】:

在你的子/函数的顶部写

'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

【讨论】:

    【解决方案2】:

    如果您已通过以下行让用户控制应用程序

    xlApp.Visible = True
    xlApp.UserControl = True
    

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

    【讨论】:

      猜你喜欢
      • 2014-12-30
      • 2018-08-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-08-13
      • 1970-01-01
      相关资源
      最近更新 更多