为什么Excel会话必须从VBA错误的Windows任务pipe理器中被终止

我有一个与VBA的Excel书。 当触发错误时,我尝试closures整个Excel应用程序。 但我发现Excel会话仍在Windows任务pipe理器中运行。 所以我必须先杀掉会话,然后才能正常重启应用程序并运行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语句,否则您将在执行结束时input代码块

err对象用于获取子/函数的错误部分中有关错误的信息。 你可以根据错误的types使用这个来做不同的事情。

例如。

 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

如果您已经通过以下行向用户提供了对应用程序的控制权限

 xlApp.Visible = True xlApp.UserControl = True 

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