VBA Nested If Statement
Nested If...Then...Else
statements allow you to create complex decision-making structures within your VBA code. This enables you to evaluate multiple conditions and execute different code blocks based on the outcome of those conditions.
Syntax:
If condition1 Then
‘ Code to execute if condition1 is True
If condition2 Then
‘ Code to execute if both condition1 and condition2 are True
Else
‘ Code to execute if condition1 is True but condition2 is 1 False
End If
Else
‘ Code to execute if condition1 is False
End If
Example
Sub CheckNumber()
Dim number As Integer
number = -10
If number > 0 Then
MsgBox "The number is positive"
Else
If number < 0 Then
MsgBox "The number is negative"
Else
MsgBox "The number is zero"
End If
End If
End Sub
Explanation:
If
condition checks if number
is greater than 0.number
is greater than 0, the inner If
condition is not executed, and the message “The number is positive” is displayed.number
is not greater than 0, the Else
block is executed.Else
block, another If
condition checks if number
is less than 0.number
is less than 0, the message “The number is negative” is displayed.number
is neither greater than 0 nor less than 0, it must be 0, so the message “The number is zero” is displayed.Key Points:
If...Then...Else
statements to create complex decision-making structures.Select Case
statements for multiple comparisons based on a single variable.