VBA Switch Statement
The Select Case statement is a powerful control flow structure in VBA that allows you to execute different code blocks based on the value of a specific expression. It’s often used as an alternative to nested If...Then...Else statements, especially when you need to compare a single expression against multiple values.
How it Works:
expression is evaluated first.Case statement.Case Else block is executed (optional).Syntax:
Select Case expression
Case value1
‘ Code to execute if expression equals value1
Case value2, value3
‘ Code to execute if expression equals value2 or value3
Case Else
‘ Code to execute if expression doesn’t match any of the cases
End Select
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:
Select Case statement is often more readable and efficient than multiple nested If...Then...Else statements.Case statements to match multiple values.Case Else block is optional and provides a default action if no match is found.Case statements to create more complex conditions.