如何自动停止VBAmacros?

我知道你可以使用Ctrl + Break手动停止正在运行的VBAmacros,但是有什么方法可以让代码自动停止,如果满足某些条件? exit function / exit sub不工作,因为他们只是终止他们被调用的方法。

例如,

 sub a call b msgbox "a complete" end sub sub b call c msgbox "b complete" 'this msgbox will still show after the `exit sub` in 'c' end sub sub c msgbox "entering c" exit sub 'this will only `exit sub` 'c', but not 'a' or 'b' msgbox "exiting c" end sub 'OUTPUT: 'entering c 'b complete 'a complete 

我想我可以将这些sub转换成function ,并利用返回代码来知道方法是否成功执行,但是有没有更简单的方法呢?

你可以用err.raise提出自己的用户定义的错误。 这与您的示例类似,但更强大一点,即使将其应用于嵌套调用,也会停止执行代码。

例如,

 sub a on error goto exitCode call b msgbox "a complete" exit sub 'you need this to prevent the error handling code from always running exitCode: msgbox "code is exiting..." 'clean up code here end sub sub b call c msgbox "b complete" end sub sub c msgbox "entering c" err.raise 555, "foo", "an error occurred" msgbox "exiting c" end sub 'OUTPUT: 'entering c 'code is exiting... 

err.raise行会将控件发送到exitCode:标签,即使它是在a之外被调用a 。 您可以使用任何条件来testing是否应引发此自定义错误。

关于err对象和VBAerror handling的更多信息 –

https://msdn.microsoft.com/en-us/library/ka13cy19(v=vs.90).aspx

http://www.cpearson.com/excel/errorhandling.htm

我相信你想要做的是在你的error handling代码中再次提出错误。 尝试像这样(未testing):

 Private Sub Test On Error Goto bad x = 0 debug.print 1/x Exit Sub bad: 'Clean up code Err.Raise Err.Number, Err.Source, Err.Description, Err.HelpFile, Err.HelpContext End Sub 

当使用On Error Goto ,你需要在标签前面有一个Exit Sub 。 否则,即使在没有错误的情况下,你的代码也会通过error handling程序。

您的第一个error handling不会捕获您正在testing的其他运行时可能发生的实际错误。 而且,除非您在所有调用例程中添加了检查,否则没有一种方便的方式来向调用函数发出信号出错的信号。

请注意,尽pipe只为stream量控制引发错误,但它通常被认为是不好的devise:

 Private Sub Test If x = 0 Then Err.Raise End If End Sub