如何自动停止VBA宏?

ili*_*ode 6 error-handling excel vba excel-vba

我知道您可以使用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
Run Code Online (Sandbox Code Playgroud)

我想我可以将这些sub变成function's并利用返回码来知道方法是否成功执行,但有更简单的方法吗?

ili*_*ode 9

您可以使用提升自己的用户定义错误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...
Run Code Online (Sandbox Code Playgroud)

该err.raise行将控件发送到exitCode:标签,即使它在外面被调用a.您可以使用任何条件来测试是否应该抛出此自定义错误.

有关err对象和VBA错误处理的更多信息 -

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

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