Select Case Examples (VBA)
Select Case (Decision Making)
Example-1
Sub WeekdayTestSelectCase()
Select Case Weekday(VBA.Date)
Case 2 'Monday
MsgBox "Ugghhh - - Back to work.", , "Today is Monday"
Case 3 'Tuesday
MsgBox "At least it's not Monday anymore!", , "Today is Tuesday"
Case 4 'Wednesday
MsgBox "Hey, we're halfway through the work week!", , "Today is Wednesday"
Case 5 'Thursday
MsgBox "Looking forward to the weekend.", , "Today is Thursday"
Case 6 'Friday
MsgBox "Have a nice weekend!", , "Today is Friday!"
Case 1, 7 'Saturday or Sunday
MsgBox "Hey, it's currently the weekend!", , "Today is a weekend day!"
End Select
End Sub
Example-2
Sub CurrentQuarter()
Select Case Month(VBA.Date)
Case 1 To 3: MsgBox "Quarter 1"
Case 4 To 6: MsgBox "Quarter 2"
Case 7 To 9: MsgBox "Quarter 3"
Case 10 To 12: MsgBox "Quarter 4"
End Select
End Sub
Example-3
Sub SelectCaseExample()
Dim PaidAttendance As Long
PaidAttendance = Range("A1").Value
Select Case PaidAttendance
Case Is < 1000: MsgBox "Small-sized crowd!"
Case Is < 5000: MsgBox "Medium-sized crowd!"
Case Is >= 5000: MsgBox "WOW! Excellent! Huge crowd!"
End Select
End Sub
Example-4
Sub SelectCaseExample()
Dim i as integer
i=inputbox("Please enter a number between 0 to 99")
Select Case i
Case < 10: MsgBox "Less than 10"
Case < 20: MsgBox "Less than 20"
Case < 30: MsgBox "Less than 30"
Case < 40: MsgBox "Less than 40"
Case < 50: MsgBox "Less than 50"
Case < 60: MsgBox "Less than 60"
Case < 70: MsgBox "Less than 70"
Case < 80: MsgBox "Less than 80"
Case < 90: MsgBox "Less than 90"
Case < 100: MsgBox "Less than 100"
Case Else: MsgBox "Wrong Number Entered"
End Select
'Note:- You may use "Case Else:" or "Case >=100:" to check for an exception.
End Sub
Example-5
Sub SelectCase()
Dim i As Integer
i = InputBox("Enter any number between 1 to 5")
Select Case i
Case 1
MsgBox "This is number 1", vbInformation
Case 2
MsgBox "This is number 2", vbInformation
Case 3
MsgBox "This is number 3", vbInformation
Case 4
MsgBox "This is number 4", vbInformation
Case 5
MsgBox "This is number 5", vbInformation
Case Else
MsgBox "Wrong number entered", vbInformation
End Select
End Sub
Comments
Post a Comment