In VBA, “Case” most commonly refers to the Select Case statement, a conditional branching structure that runs different code blocks depending on the value of an expression. It is the cleaner, more readable alternative to nested If...ElseIf chains when you need to compare one value against several possibilities.
What Is Select Case and Why Use It?
Select Case evaluates an expression once and then compares that result against a series of Case clauses. The first matching clause runs its code, and then execution jumps to the line after End Select. This avoids re-evaluating the same expression multiple times, which makes the code faster and easier to read.
For example, imagine you want to assign a letter grade based on a numeric score. With If you would write:
If score >= 90 Then
grade = "A"
ElseIf score >= 80 Then
grade = "B"
ElseIf score >= 70 Then
grade = "C"
Else
grade = "F"
End If
The same logic with Select Case is clearer:
Select Case score
Case Is >= 90
grade = "A"
Case Is >= 80
grade = "B"
Case Is >= 70
grade = "C"
Case Else
grade = "F"
End Select
Notice the Case Is >= 90 syntax: when you need a comparison operator (like >, <, <>) you must use Case Is followed by the operator and value. If you are checking for exact equality, you can just write Case 90.
Case Sensitivity and the Option Compare Statement
By default, VBA string comparisons are case-insensitive. That means Case "apple" will match “Apple”, “APPLE”, and “apple”. If you need case-sensitive matching, add Option Compare Binary at the top of the module, before any procedures. Conversely, Option Compare Text forces case-insensitive comparisons even if the system locale would otherwise use binary.
This behavior is determined at module level, so you cannot change it inside a procedure. If you have a mix of case-sensitive and case-insensitive needs in the same module, consider using StrComp with the vbBinaryCompare or vbTextCompare argument inside a Select Case on the result.
Using Case Else and Multiple Values per Case
The Case Else clause is optional but strongly recommended. It catches any value that did not match any earlier case, preventing unexpected behavior. If no Case Else exists and no case matches, the procedure simply continues after End Select without running any code.
You can also list several values in a single Case clause, separated by commas. This is handy when multiple distinct values should trigger the same action:
Select Case dayNumber
Case 1, 7
msg = "Weekend"
Case 2, 3, 4, 5, 6
msg = "Weekday"
Case Else
msg = "Invalid day"
End Select
You can also use the To keyword for a range of values:
Case 1 To 5
msg = "Low"
Case 6 To 10
msg = "High"
Select Case vs. If-ElseIf: Which Should You Choose?
The choice depends on the situation. Use Select Case when you are comparing a single expression against multiple discrete values or ranges. It is more readable and avoids repeating the variable name. Use If...ElseIf when you have complex conditions that involve multiple variables or logical operators like And and Or.
For example, a condition like If x > 0 And y < 0 Then cannot be rewritten cleanly with Select Case. However, if you have a variable that can take one of many known values, Select Case is almost always the better choice.
Common Errors and Pitfalls
One frequent mistake is forgetting the Is keyword when using comparison operators. Writing Case >= 90 causes a compile error. Always write Case Is >= 90.
Another pitfall is using Select Case with a variable that can be Null (in a database context) or an uninitialized Variant. If the expression is Null, no case will match, and execution falls to Case Else (if present) or continues after End Select. To avoid surprises, check for Null before the Select Case.
A third issue is performance: Select Case is not automatically faster than If in all scenarios, but it is usually at least as fast and often clearer. Do not micro-optimize; prioritize readability.
Case in Other Contexts: UCase, LCase, and StrConv
Besides Select Case, the word “case” appears in VBA functions that change the capitalization of strings. UCase converts a string to uppercase, LCase to lowercase, and StrConv can convert to proper case (first letter of each word capitalized) using vbProperCase.
For example:
Dim lower As String
lower = "hello world"
MsgBox UCase(lower) ' shows HELLO WORLD
MsgBox StrConv(lower, vbProperCase) ' shows Hello World
These functions are often used to normalize user input before comparing, so that a Select Case works reliably regardless of how the user typed the data.
Frequently Asked Questions
Can I use Select Case with strings? Yes, Select Case works with strings. Just write Case "apple" or Case "a" To "m". Remember that string comparisons are case-insensitive by default, unless you use Option Compare Binary.
Is there a limit to the number of Case clauses? No hard limit, but extremely long Select Case blocks can become hard to read. If you have dozens of cases, consider using a lookup table (e.g., a Dictionary or a worksheet range) instead.
Can I use Select Case on a range of dates? Yes, but dates are stored as numbers. You can compare using Case Is >= DateSerial(2025, 1, 1) or use Case #1/1/2025# To #12/31/2025#.
What happens if two Case clauses match? Only the first matching clause executes. VBA does not check subsequent clauses after a match is found. This is why order matters: put more specific cases before broader ones.
Can I use Select Case inside a loop? Absolutely. It is common to place Select Case inside a For or Do loop to process each cell or element differently based on its value.
Does Select Case work with Boolean values? Yes, you can write Case True or Case False. However, for simple boolean checks, an If statement is usually simpler.
Practical Example: Processing Worksheet Data
Here is a complete macro that uses Select Case to categorize values in column A and write the category in column B. Save a copy of your workbook before running any macro, because macros cannot be undone with Ctrl+Z.
Sub CategorizeValues()
Dim cell As Range
Dim category As String
' Loop through cells A1:A10
For Each cell In Range("A1:A10")
' Skip empty cells
If IsEmpty(cell) Then GoTo NextCell
' Determine category based on numeric value
Select Case cell.Value
Case Is < 0
category = "Negative"
Case 0
category = "Zero"
Case 1 To 100
category = "Small"
Case 101 To 1000
category = "Medium"
Case Else
category = "Large"
End Select
' Write category to column B
cell.Offset(0, 1).Value = category
NextCell:
Next cell
End Sub
This macro assumes your data is in A1:A10. It checks each cell, skips blanks, and writes a category label in the adjacent cell. Notice the GoTo NextCell to skip empty cells; alternatively you could use If Not IsEmpty(cell) Then to wrap the whole logic.
In summary, Select Case is a powerful, readable way to handle multiple conditions in VBA. Use it whenever you are comparing one expression against several possible values, and remember the Is keyword for comparison operators. With practice, you will find it becomes one of your most used VBA tools.
Related
- Data Entry and Data Management: Clear Answers
- Google Sheets Percentage of Total: Easy Formula
- Java String Length: How to Get String Length
Try it: the Column Letter to Number: aA is 27, XFD is 16,384. Converts both ways.
More in VBA & macros
- Excel VBA: Check Whether a Cell Contains TextTo check whether a cell contains a particular string in Excel VBA, use InStr and test whether its…
- Google Sheets Macros: How They Work and How to Use ThemYes. Google Sheets supports macros: you can record a sequence of spreadsheet actions and replay it, or customize…
- VBA AutoFilter Sort: Filter and Sort Rows in ExcelTo filter and sort rows with VBA, apply an AutoFilter to the data range, then use the worksheet’s…
- VBA InputBox Prompt: Syntax, Examples, and Common FixesIn VBA, use the InputBox function to display a prompt and collect text from a user: assign its…
- Excel VBA Option Explicit: What It Does and How to Use ItOption Explicit is a VBA module setting that requires you to declare variables before using them. Put it…
- Excel VBA Export Chart: Image, PDF, and OptionsTo export an embedded Excel chart with VBA as a PNG, call its Chart.Export method and specify a…
Sources: Function behaviour and menu paths: Microsoft Support documentation for Excel. Method & sources
Spotted an error in this guide? Let us know.