【问题标题】:Exit VBA Main Subroutine from Called Subroutine从被调用的子程序中退出 VBA 主子程序
【发布时间】:2018-06-23 12:30:49
【问题描述】:

我有一个 sub“main”,它调用 sub“prepare”以及其他子例程。如果满足条件,我在“准备”中有一个 if 语句退出子。但是,它只退出该特定子程序,然后继续执行“main”中的所有其他子程序。

    If oAltIDLocationDictionary.Exists(sAltID) Then
        MsgBox "It appears that there are two duplicate ID's in your alternate ID list.  Duplicate ID's cannot be processed, please consolidate the location information into a single ID or remove the duplicate ID from the Alt-ID list."
        Exit Sub
    End If

有没有办法从它正在调用的“prepare”子程序中退出“main”,以便在“prepare”子程序中满足条件时,“main”子程序停止并且不再执行代码?

【问题讨论】:

  • 你可以使用End
  • 成功了!它在一分钟前不起作用,我收到一个错误,表明 if 语句没有正确结束,但它刚刚起作用。
  • 谢谢!如果您将其作为答案,我会将其标记为已接受的答案。
  • 我想借此机会强调一下函数的使用。如果你的 Sub 是一个函数,你可以让它在退出时返回一个特定的值 - 然后 Main 中的其余代码或任何可能表现不同的代码。这是一个很好的概念,似乎你正处于一个可以学习并派上用场的阶段......
  • @jamheadart 同意。 End 本质上是一个大红色按钮,它可以破坏整个运行时上下文(即将任何全局状态重置为默认值)。我从来没有需要使用End,甚至一次 - 正确的答案是正确的控制流,而不是大红色按钮。跨度>

标签: vba excel if-statement exit


【解决方案1】:

要立即停止执行宏,而不返回调用过程,您可以使用End 语句。

【讨论】:

  • 正如@mats-mug 在他对原始问题的评论中指出的那样,使用End 就像一个红色的大按钮,可以摧毁一切,并清除您的代码开发的任何状态..跨度>
【解决方案2】:

您可以将subs转换为函数,如果函数返回某个值,则main sub将退出。

Sub Main()
    Dim bTest As Boolean

    ' blah blah

    bTest = Prepare
    If bTest Then Exit Sub

    ' blah blah

End Sub

Function Prepare() As Boolean

    Prepare = False

    If oAltIDLocationDictionary.Exists(sAltID) Then
        MsgBox "It appears that there are two duplicate ID's in your alternate ID list."
        Prepare = True
        Exit Function
    End If

End Function

【讨论】:

    最近更新 更多