VBA Select Case: one value, many cases

When a value falls into one of several bands, an If with a string of ElseIf soon gets hard to read. Select Case tests one value against a list of cases and runs the first one that matches. Typical uses are discount tiers, commission rates, reminder levels and assigning cities to territories.

In short: Select Case value, then cases such as Case Is >= 100, Case 50 To 99, Case "Boston", "Baltimore" and Case Else, closed by End Select. Only the first matching case runs.

What you need to know: If Then Else, For Next and find the last row.

Try it right now

The price breaks are listed next to the order. The macro should fill in the right discount, and it has to work for a different quantity too.

Task The macro Discount should look up the order quantity in B1 and write the discount from the price breaks into B2: 100 units or more 10%, 50 to 99 units 5%, 20 to 49 units 2%, otherwise 0. In code, write percentages as decimals, so 10% is 0.1. Use Select Case with Case Is and Case … To ….

ABCDE
1Order quantity64Price breaks
2Discount100 or more10%
350 to 995%
420 to 492%
5under 200%

How Select Case is built

Select Case Range("B1").Value
    Case Is >= 100
        Range("B2").Value = 0.1
    Case 50 To 99
        Range("B2").Value = 0.05
    Case 20 To 49
        Range("B2").Value = 0.02
    Case Else
        Range("B2").Value = 0
End Select
Casematches when the value …Example
Case 5is exactly 5month of May
Case 50 To 99is between 50 and 99, both includedquantity break
Case Is >= 100passes the comparison (=, <>, <, >, <=, >=)100 units or more
Case "Boston", "Baltimore"equals one of the entriescities in a territory
Case 1 To 4, 10, Is > 20matches any of the parts (you can mix them)special cases
Case Elsedid not match any case aboveeverything else

VBA works through the cases from top to bottom. The first match runs, then the macro jumps past End Select. Even if a later case would also match, it never gets a turn. Case Else is optional, but you almost always want it: without it, an unexpected value simply does nothing.

If you type Case >= 100 without Is, the VBA editor adds the Is for you when you leave the line.

Select Case or If?

Here is the same set of price breaks written with If:

If qty >= 100 Then
    discount = 0.1
ElseIf qty >= 50 Then
    discount = 0.05
ElseIf qty >= 20 Then
    discount = 0.02
Else
    discount = 0
End If

Both are correct. Select Case pays off once you keep testing the same value and there are more than two or three cases. When the cases depend on different values (quantity and customer group), If is still the better tool.

Lists: several values for one case

Separate values with commas and one case covers them all. With If you would need a long chain of Or. Select Case compares text exactly, including upper and lower case: "boston" is not "Boston". How to tidy up text first is covered in string functions.

Task Each customer is assigned to a sales territory. The macro Territories should check the city in column B on every row down to the last one and fill in column C: Boston, New York, Philadelphia and Baltimore are East, Seattle, Portland, San Francisco and Sacramento are West, every other city is Central.

ABCD
1CustomerCityTerritory
2Harbor Freight LinesBoston
3Lakeside BrewingChicago
4Pacific DeliSeattle
5Hudson SailmakersNew York
6Summit EventsDenver
7Rose City ToolsPortland

This exercise is part of Premium.

Premium unlocks every exercise in every lesson, unlimited practice with fresh tasks and the final test with certificate.

See Premium Already Premium? Log in

The first exercise in this lesson is free.

Ranges and boundaries

With tiers, the boundaries are what matter. Case 1 To 14 includes both 1 and 14, so the next band starts at 15, not 14. Check tests exactly those edge values. With decimals, 1 To 14 and 15 To 30 leave a gap: 14.5 matches neither. In that case Case Is <= 14 followed by Case Is <= 30 is safer.

Task The macro ReminderLevels should go through every invoice down to the last row and, based on the days in column C, write the level into column D: 0 days or fewer Not due, 1 to 14 days Reminder, 15 to 30 days First notice, more than 30 days Final notice.

ABCD
1InvoiceCustomerDays overdueLevel
2INV-1041Carter Bakery-5
3INV-1042Peters Motors3
4INV-1043Riverside Dental14
5INV-1044Green Leaf Garden Centre21
6INV-1045Hotel Marlow47
7INV-1046Brandt & Co Law0

This exercise is part of Premium.

Premium unlocks every exercise in every lesson, unlimited practice with fresh tasks and the final test with certificate.

See Premium Already Premium? Log in

The first exercise in this lesson is free.

Common mistakes

Forgetting End Select

Without End Select, VBA reports "Compile error: Select Case without End Select" before the macro runs.

Cases in the wrong order

If Case Is >= 20 comes before Case Is >= 100, every quantity from 20 up lands in the first case, 120 included. The exercise then says "B2 contains 0.02, expected: 0.05." With Is comparisons, put the strictest case first.

Or instead of a comma

Case "Boston" Or "Seattle" tries to combine two pieces of text with Or and stops with "Run-time error '13': Type mismatch". Separate values with a comma: Case "Boston", "Seattle".

A hyphen instead of To

To VBA, Case 50 - 99 is a sum: 50 minus 99 is -49. The case then only matches -49, and there is no error message. Always write ranges with To, smaller value first.

In real Excel

Tiers change. If the limits are hard-coded, someone has to edit the macro every time. For values that change often, a tier table on the sheet that the macro reads is the better design. For fixed rules, such as mapping months to quarters, Select Case is the most readable option.

FAQ

Can a case run several statements?

Yes, any number of lines can go under a Case, including an If or a loop. They apply until the next Case.

Does To work with text?

Yes, Case "A" To "M" matches text that sorts between the two. Watch out: "Miller" sorts after "M" and therefore no longer matches. For first letters, the Left function from level 3 is a better fit.

What happens without Case Else when nothing matches?

No case runs, and the macro carries on after End Select. The cell stays empty. That is rarely what you want, so add a Case Else almost every time.

Can Select Case be nested?

Yes, a case can contain another Select Case, each with its own End Select. Beyond two levels it gets hard to follow; a function of your own, covered in level 3, helps then.

Learn this next: Offset and Resize

Refer to cells relative to another one: one column across, one row down, a block from a starting cell. That is how you put a total row right under a list.

Learn Offset and Resize

Write to us

Choose language

Select your preferred language