Search
Close this search box.

VBA If Else Statement


The If...Then...Else statement is a fundamental control flow structure in VBA that allows you to execute different code blocks based on a specific condition.

How it Works:

  1. Condition: The condition is an expression that evaluates to either True or False.
  2. True Block: If the condition is True, the code within the Then block is executed.
  3. False Block (Optional): If the condition is False, the code within the Else block is executed.

Syntax:

If condition Then ‘ Code to execute if condition is True Else ‘ Code to execute if condition is False End If

Example

				
					Sub CheckNumber()
    Dim number As Integer
    number = 10

    If number > 5 Then
        MsgBox "The number is greater than 5"
    Else
        MsgBox "The number is less than or equal to 5"
    End If
End Sub
				
			

Explanation:

  1. The variable number is assigned the value 10.
  2. The If condition checks if number is greater than 5.
  3. Since 10 is greater than 5, the code within the Then block is executed, displaying the message “The number is greater than 5”.

Key Points:

  • The Else part is optional. If omitted, the code will simply continue to the next line after the If...Then block if the condition is false.
  • You can nest multiple If...Then...Else statements to create complex decision-making structures.
  • Use indentation to improve code readability.