How to Use Exit IF Statement in VBA (With Example)


There is no built-in Exit If statement in VBA but you can easily simulate one by using an If statement with a GoTo statement.

The following example shows how to do so in practice.

Example: How to Use Exit IF Statement in VBA

Suppose we would like to create a macro that asks the user to enter an integer less than 10 and then use an IF statement to do the following:

  • If the integer entered is less than 10, multiply it by 2 and display the result in cell A1.
  • If the integer entered is not less than 10, exit the IF statement and produce an error message.

We can use the following syntax to do so:

Sub MultiplySomeValue()

Dim inputInteger As Integer
     
'get integer from user
inputInteger = InputBox("Please enter an integer less than 10")

'check if integer is less than 10
If inputInteger < 10 Then
Range("A1").Value = inputInteger * 2
Else
GoTo FlagMessage
End If

FlagMessage:
MsgBox "This number is not less than 10"
    
End Sub

When we run this macro, we will be prompted to enter an integer less than 10:.

Suppose we enter the value 5 and then press OK:

Since this integer is less than 10, the sub procedure will multiply the value we entered by 2 and display the result in cell A1:

However, suppose we entered a value of 15 instead:

We would receive the following message box in Excel:

The value that we entered would not be multiplied by 2 and no result would be displayed in cell A1.

Additional Resources

The following tutorials explain how to perform other common tasks in VBA:

How to Exit Sub on Error in VBA
How to Use IFERROR in VBA
How to Delete Files Using VBA

Leave a Reply

Your email address will not be published. Required fields are marked *