Skip to content

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.

VBA
Sub RouteInvoice()
If Range("C2").Value > 5000 Then
Range("D2").Value = "Finance director"
ElseIf Range("C2").Value > 500 Then
Range("D2").Value = "Manager"
Else
Range("D2").Value = "Pay"
End If
End Sub
Writes who approves the invoice amount in C2, in D2.

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> 500D2 shows
$8,000Truenot checkedFinance director
$5,000FalseTrueManager
$2,300FalseTrueManager
$500FalseFalsePay
VBA checks the tests from the top and stops at the first one that's true. With >, 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 >= 100 compares, Case 50 To 99 takes a range with both ends included, and Case Else takes the rest.

VBA
Sub QuantityDiscount()
Select Case Range("B2").Value
Case Is >= 100
Range("C2").Value = 0.1
Case 50 To 99
Range("C2").Value = 0.05
Case Else
Range("C2").Value = 0
End Select
End Sub
Sets the discount in C2 from the quantity ordered in B2.

Common mistakes

  • Testing the lower band first. If amount > 500 catches the $8,000 invoices too, and the director never sees them.
  • If Range("E2").Value = "paid" when the cell holds Paid. VBA compares text with its capitals, so the test is False; compare with LCase(Range("E2").Value) = "paid" or match the cell's text exactly.
  • A missing End If or End Select. VBA won't run the macro until each block is closed.

In short

  • If, ElseIf and Else run the lines under the first test that's true.
  • Put the highest band first, and check which band the boundary value lands in.
  • Select Case picks between bands of one value; text tests count capitals.

Practice

Premium

4 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.