如何自动停止VBA宏?

时间:2014-10-14 19:33:39

标签: excel vba excel-vba error-handling

我知道您可以使用 Ctrl + Break 手动停止正在运行的VBA宏,但是如果满足某个条件,有没有办法让代码自动停止? 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并使用返回码来了解方法是否成功执行,但是有更简单的方法吗?此?

3 个答案:

答案 0 :(得分: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...

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

答案 1 :(得分:1)

我相信你想要做的就是在你的错误处理代码中再次提出错误。尝试这样的事情(未经测试):

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。否则,即使没有错误,您的代码也会进入错误处理程序。

您的第一个错误处理不会捕获运行期间可能发生的实际错误,而不是您正在测试的错误。此外,除非在所有调用例程中添加检查,否则没有一种方便的方法来向调用函数发出错误信号。

请注意,虽然仅为流量控制引发错误,但通常认为它设计不好:

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

答案 2 :(得分:0)

您可以创建宏以执行以下步骤/操作,并在代码满足特定条件时调用以中止其他正在运行的宏:

步骤1-菜单栏->运行->重置

第2步-菜单栏->运行->中断