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
Search our website
We also send out useful tips in a monthly email newsletter ...
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.
This series of blogs is part of our Excel VBA online tutorial. Alternatively, why not have a look at our Excel courses or VBA training?
|
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:
Sub TestDay()
'display different messages for different days of the week
Select Case Weekday(Date)
Case vbFriday
'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"
Case vbMonday
'it's Monday ...
MsgBox "Sorry - it's Monday"
Case Else
'it must be mid-week
MsgBox "Not long till Friday"
End Select
End Sub
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 |
---|
|
Some other pages relevant to the above blogs include:
Kingsmoor House
Railway Street
GLOSSOP
SK13 2AA
Landmark Offices
99 Bishopsgate
LONDON
EC2M 3XD
Holiday Inn
25 Aytoun Street
MANCHESTER
M1 3AE
© Wise Owl Business Solutions Ltd 2023. All Rights Reserved.