556 attributed reviews in the last 3 years
Refreshingly small course sizes
Outstandingly good courseware
Whizzy online classrooms
Wise Owls only (no freelancers)
Almost no cancellations
We have genuine integrity
We invoice after training
Review 30+ years of Wise Owl
View our top 100 clients
Conditions in Visual Basic for Applications - IF and SELECT CASE
Part three of a three-part series of blogs
This part of the Excel VBA training series of blogs shows how to use IF / ELSE / END IF within VBA, and also how to use the alternative SELECT / CASE syntax within macros.
Rather than using IF statements, it's often clearer to use SELECT CASE instead (called SWITCH in some other languages). This tests the value of a variable or expression, then reacts differently for different values of it. For example:
'display different messages for different days of the week
Select Case Weekday(Date)
'it's the end of the week
MsgBox "Hooray - it's Friday!"
Case vbSunday, vbSaturday
'it's the weekend
MsgBox "Yeah! It's the weekend"
'it's Monday ...
MsgBox "Sorry - it's Monday"
'it must be mid-week
MsgBox "Not long till Friday"
In the above macro, we evaluate the day of the week using Weekday(Date), then test this against various possible day numbers.
You don't need a Case Else statement, although it's good practice always to include one. Often it's a good idea to report an error in the Case Else clause, since if your code reaches it you must have failed to include all possible eventualities.
|Parts of this blog|
25 Aytoun Street