VBA exit if statement

If you operating with loops, there is a way you can leave the loop based on certain criteria. You can use Exit For or Exit Do, but there is no Exit If.

If the statement doesn’t represent a loop, but a conditional statement, therefore it doesn’t offer such a construct.

It doesn’t mean you can’t simulate it.

In many languages, there is a GoTo statement. It’s not recommended to use GoTo because it makes code harder to read and you can always modify your code, so there is no need to use it.

But there is GoTo, so I’ll tell you how to implement it into your code.

In this example, you can see how this code looks like.

Sub SimulateExitIf()
    Dim myvar As Integer
     
    myvar = 4
     
    If myvar < 6 Then
        GoTo flag1
    End If
     
flag1:
    MsgBox "The number is lower than 6"
End Sub

Excel checks whether the myvar variable is lower than 6. If it’s lower than the GoTo statement is executed and moves interpreter to flag1. In other words: It leaves the If statement.

Posted in vba