终止宏从进一步执行验证

时间:2013-02-12 07:08:26

标签: vba excel-vba excel

我有一个method-A()来自多种方法,

在方法A的条件下,我必须终止宏。

我看到一个选项Exit sub,但这只会退出当前的sub ie:method-A(),剩下的程序会继续。

如何处理这个问题。

Sub mainMethod()
    method-A()
end Sub

Sub method-A()
    if (true) Then
         'Terminate the macro. that is exit method-A() and also mainMethod()
end Sub

1 个答案:

答案 0 :(得分:19)

评论后编辑:     只需使用end即可终止所有代码。

Sub mainMethod()
    method_A()
end Sub

Sub method-A()
    if (true) Then End
         'Terminate the macro. that is exit method-A() and also mainMethod()
end Sub

原始答案:您需要做的就是将methodA设为函数,如果要按照以下代码退出main方法,则将此函数返回为FALSE:

Sub mainMethod()

    'Run the custom function and if it returns false exit the main method
    If Not method_A Then Exit Sub

    'If method_A returns TRUE then the code keeps going
    MsgBox "Method_A was TRUE!"

End Sub

Function method_A() As Boolean
    Dim bSomeBool As Boolean

   'Code does stuff
   bSomeBool = True

   'Check your condition
   If bSomeBool Then
       'Set this function as false and exit
       method_A = False
       Exit Function
   End If

    'If bSomeBool = False then keep going
End Function