Mis*_*cro 1 excel vba excel-vba
我正在寻求您的帮助。好吧,我有一个细分为很多过程
Sub Go
Call Proc1
Call Proc2
Call Proc3
Call Proc4
End Sub
Run Code Online (Sandbox Code Playgroud)
在Proc1中,我进行值的匹配,并检查单元格是否为空等。因此,如果任何条件不正确,我想退出Sub Go并停止运行宏。
我测试了End,Exit Sub,但是它只是从测试1到测试2。
有什么方法可以直接转到最后一个End Sub(即Sub Go!)。
解决方案1:将Sub更改为Functions:
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
Run Code Online (Sandbox Code Playgroud)
解决方案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
Run Code Online (Sandbox Code Playgroud)
解决方案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
Run Code Online (Sandbox Code Playgroud)