vba 终止宏 进一步执行验证

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14827273/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 14:56:47  来源:igfitidea点击:

Terminating Macro From executing further on validation

vbaexcel-vbaexcel

提问by Naveen Babu

I have a method-A()that is called from multiple methods,

我有一个method-A()从多种方法调用的,

On a condition in method-A, i have to terminate the macro.

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

i saw one option as Exit subbut this will just exit the current sub ie:method-A()and the remaining program continues.

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

how to handle this.

如何处理这个。

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

回答by CuberChase

Edit after comment: Just use endwhere you want to terminate ALL code.

评论后编辑:只需使用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

Original Answer: All you need to do is make methodA a function and return this function as FALSE if you want to exit the main method as per the following code:

原始答案:如果您想按照以下代码退出 main 方法,您需要做的就是使 methodA 成为一个函数并将此函数返回为 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