Ravindra BagaleCourses & study guides

12. Macros and VBA

12.9 If and Select Case

Sub ClassifyDelivery()
    Dim mins As Double
    mins = Worksheets("Orders").Range("H2").Value

    If mins <= 10 Then
        MsgBox "Excellent (10-minute delivery)"
    ElseIf mins <= 15 Then
        MsgBox "Good"
    Else
        MsgBox "Late - check with store"
    End If
End Sub

Function CityCode(ByVal city As String) As String
    Select Case Trim(city)
        Case "Pune": CityCode = "PUN"
        Case "Nashik": CityCode = "NSK"
        Case "Nagpur": CityCode = "NGP"
        Case "Kolhapur": CityCode = "KOP"
        Case "Solapur": CityCode = "SLP"
        Case "Sambhaji Nagar", "Aurangabad": CityCode = "SBN"
        Case Else: CityCode = "UNK"
    End Select
End Function

Select Case also accepts ranges and comparisons: Case 0 To 98, Case Is >= 499.

Ravindra Bagale's Tip

In VBA, text comparison is case-sensitive by default – "pune" and "Pune" are different! That's why many students' Select Case returns "UNK". Before comparing, use Trim and LCase/UCase, or write Option Compare Text at the top of the module. ElseIf is one word – if you write "Else If", it creates a separate block.

Practice task

Write a macro that reads the Status in I2 and uses Select Case to colour the row green (Delivered), grey (Cancelled) or orange (Returned).