我正在寻求你的帮助。 好吧,我有一个分为很多proc
Sub Go
Call Proc1
Call Proc2
Call Proc3
Call Proc4
End Sub
在Proc1中,我进行了值的匹配,并检查单元格是否为空等。所以我想退出Sub Go并在任何条件为真的情况下停止运行宏。
我测试了End,Exit Sub,但它只是从测试1到测试2。
是否有任何方法直接转到最后一个End Sub(即Sub Go!)
答案 0 :(得分:4)
解决方案1:将子功能更改为
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
解决方案2:提升并发现错误
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
解决方案3:使用全局变量
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
答案 1 :(得分:3)
这是一种方式:
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 |假。使用它来测试成功并退出sub,如果不是。
答案 2 :(得分:1)
您可以按如下方式使用全局变量:
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