我知道您可以使用Ctrl+手动停止正在运行的VBA宏Break,但是如果满足特定条件,有什么办法可以使代码自动停止?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
。您可以使用任何条件来测试是否应引发此自定义错误。
有关err
对象和VBA错误处理的更多信息-
https://msdn.microsoft.com/zh-CN/library/ka13cy19(v=vs.90).aspx
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句