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.
Ravindra Bagale's Tip – मराठी
VBA मध्ये text comparison default case-sensitive असतं – "pune" आणि "Pune" वेगळे! म्हणून बऱ्याच students चा Select Case "UNK" देतो. Compare करण्याआधी Trim आणि LCase/UCase वापरा, किंवा module च्या वरती Option Compare Text लिहा. ElseIf एक शब्द आहे – "Else If" लिहिलं तर वेगळा block बनतो.
Ravindra Bagale's Tip – हिंदी
VBA में text comparison default रूप से case-sensitive होता है – "pune" और "Pune" अलग! इसीलिए बहुत से students का Select Case "UNK" देता है. Compare करने से पहले Trim और LCase/UCase इस्तेमाल करो, या module के ऊपर Option Compare Text लिखो. ElseIf एक शब्द है – "Else If" लिखा तो अलग 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).