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:
condition
is an expression that evaluates to either True
or False
.True
, the code within the Then
block is executed.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:
number
is assigned the value 10.If
condition checks if number
is greater than 5.Then
block is executed, displaying the message “The number is greater than 5”.Key Points:
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.If...Then...Else
statements to create complex decision-making structures.