Make decisions with If and Select Case
Write VBA9 minPremium
Builds on Store values in variables, and shorten code with With.
Accounts payable at a building-supplies company in Raleigh routes every invoice by its amount: over $5,000 goes to the finance director, over $500 to a manager, and the rest is paid straight away. The macro writes the right step next to each invoice.
How it works
If runs lines only when a test is true. VBA checks the tests from the top, runs the lines under the first one that's true, and then skips to End If. Else catches everything the tests above it didn't.
Sub RouteInvoice() If Range("C2"). Value > 5000 Then Range("D2"). Value = "Finance director" ElseIf Range("C2"). Value > 500 Then Range("D2"). Value = "Manager" ElseRange("D2"). Value = "Pay" End IfEnd Sub
Order matters: every invoice over $5,000 is also over $500, so the higher band has to be tested first. Tests use =, <>, <, <=, > and >=, and And and Or join two of them. The boundaries follow the signs exactly: an invoice of exactly $5,000 isn't over $5,000, so it goes to a manager.
| C2 | > 5000 | > 500 | D2 shows |
|---|---|---|---|
| $8,000 | True | not checked | Finance director |
| $5,000 | False | True | Manager |
| $2,300 | False | True | Manager |
| $500 | False | False | Pay |
>, exactly $5,000 goes to a manager, and exactly $500 is paid.When one value decides between several bands, Select Case reads more easily. VBA runs the first Case that matches: Case Is >= compares, Case 50 To 99 takes a range with both ends included, and Case Else takes the rest.
Sub QuantityDiscount() Select Case Range("B2"). Value Case Is >= 100Range("C2"). Value = 0. 1 Case 50 To 99Range("C2"). Value = 0. 05 Case ElseRange("C2"). Value = 0 End SelectEnd Sub
Common mistakes
- Testing the lower band first.
If amount >catches the $8,000 invoices too, and the director never sees them.500 If Range(when the cell holds Paid. VBA compares text with its capitals, so the test is False; compare with"E2").Value = "paid" LCase(or match the cell's text exactly.Range( "E2").Value) = "paid" - A missing
End IforEnd Select. VBA won't run the macro until each block is closed.
In short
If,ElseIfandElserun the lines under the first test that's true.- Put the highest band first, and check which band the boundary value lands in.
Select Casepicks between bands of one value; text tests count capitals.
Practice
Premium4 exercises: 3 macros and 1 quiz question.
Practice is part of Premium
Every lesson is free to read, and you can practice the free lessons without an account. This lesson's exercises are part of Premium, which you add to a free account.
Have one? Sign in