VBA – 如果条件不成立,如何退出一个整体

我正在寻求你的帮助。 那么我有一个分为很多proc的子

Sub Go Call Proc1 Call Proc2 Call Proc3 Call Proc4 End Sub 

在Proc1中,我做了匹配的值,并检查单元格是否为空等,所以我想退出子去,并停止macros运行,如果任何条件不成立。

我testing了End,Exit Sub,但它只是从testing1到testing2。

是否有任何方法直接去最后的小组(即子去!)

解决scheme1:将Sub更改为函数:

 Function Proc1() As Boolean 'Do some check If SomeCheckAreWrong Then Proc1 = False Else 'Normal treatment Proc1 = True End If End Function Sub Go() If Proc1 Then 'do proc2 only if proc1 returned True If Proc2 Then '... End If End If End Sub 

解决scheme2:提高和捕获错误

 Sub Proc1() 'Do some check If SomeCheckAreWrong Then Err.Raise vbObjectError + 1 Else 'Normal treatment End If End Sub Sub Go() On Error GoTo exit_with_error Proc1 Proc2 '... exit_with_error: End Sub 

解决scheme3:使用全局variables

 Global DoNotContinue As Boolean Sub Proc1() 'Do some check If SomeCheckAreWrong Then DoNotContinue = True Else 'Normal treatment End If End Sub Sub Go() DoNotContinue = False Proc1 If DoNotContinue Then Exit Sub Proc2 If DoNotContinue Then Exit Sub '... End Sub 

这是一个方法:

 Sub Main() If Not Proc1 Then Exit Sub End If If Not Proc2 Then Exit Sub End If Debug.Print "Done" End Sub Function Proc1() As Boolean Dim matchVal As String matchVal = "A" Proc1 = IIf(Range("A1") = matchVal, True, False) End Function Function Proc2() As Boolean Dim matchVal As String matchVal = "B" Proc2 = IIf(Range("B1") = matchVal, True, False) End Function 

每个函数都返回一个布尔值,即True | 假。 使用这个来testing成功,如果不是,退出子。

您可以使用全局variables,如下所示:

 Public IsExit As Boolean Sub Proc1() 'your stuff here IsExit = True End Sub Sub Gom() IsExit = False Call Proc1 If IsExit Then Exit Sub Call Proc2 If IsExit Then Exit Sub Call Proc3 If IsExit Then Exit Sub Call Proc4 End Sub