MissMacro
MissMacro

Reputation: 41

VBA - How do exit a whole sub if a condition isn't true

I'm seeking for your help. Well I have a sub divided in a lot of proc

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

In the Proc1 I do the matching of values and I check if the cells are empty etc. So I want to Exit the Sub Go and stop the macro from running if any condition isn't true.

I tested End, Exit Sub but it just goes from the test 1 to the test 2.

Is there any method the go directly to the last End Sub (i.e Sub Go ! )

Upvotes: 2

Views: 32741

Answers (3)

Vincent G
Vincent G

Reputation: 3188

Solution 1: Changing Sub to 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

Solution 2: Raising and catching error

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

Solution 3: With global variable

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

Upvotes: 5

Mrig
Mrig

Reputation: 11712

You can use a global variable as follows:

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

Upvotes: 1

Alex P
Alex P

Reputation: 12497

Here is one way:

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

Each function returns a boolean i.e True | False. Use this to test for success and exit the sub if not.

Upvotes: 3

Related Questions