Search
Close this search box.

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:

  1. Condition 1: The first 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.
  2. Condition 2: If the first condition is 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.
  3. Subsequent Conditions: This process continues for each ElseIf condition until a True condition is found or all conditions are False.
  4. Else Block: If none of the conditions are 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:

  • The ElseIf clause allows you to check multiple conditions sequentially.
  • The Else clause is optional and provides a default action if none of the previous conditions are met.
  • You can nest If...ElseIf...Else statements to create more complex decision-making structures.