VBA If Elseif Else Statement
The If...ElseIf...Else statement is a powerful control flow structure in VBA that allows you to execute different code blocks based on multiple conditions. It’s an extension of the basic If...Then...Else statement, providing more flexibility for complex decision-making.
How it Works:
If condition is evaluated. If it’s True, the code within the first Then block is executed, and the rest of the ElseIf and Else blocks are skipped.False, the second ElseIf condition is evaluated. If it’s True, the code within its Then block is executed, and the remaining ElseIf and Else blocks are skipped.ElseIf condition until a True condition is found or all conditions are False.True, the code within the Else block is executed.Syntax:
If condition1 Then ‘ Code to execute if condition1 is True ElseIf condition2 Then ‘ Code to execute if condition1 is False and condition2 is True ElseIf condition3 Then ‘ Code to execute if condition1 and condition2 are False, but condition3 is True Else ‘ Code to execute if none of the above conditions are True End If
Example
Sub CheckGrade()
Dim grade As String
grade = "B"
Select Case grade
Case "A"
MsgBox "Excellent!"
Case "B", "C"
MsgBox "Good job!"
Case "D", "F"
MsgBox "Needs improvement."
Case Else
MsgBox "Invalid grade."
End Select
End Sub
Key Points:
ElseIf clause allows you to check multiple conditions sequentially.Else clause is optional and provides a default action if none of the previous conditions are met.If...ElseIf...Else statements to create more complex decision-making structures.