Microsoft Office Tutorials and References
In Depth Information
Choosing Between This or That
NOT operator in this way, you get the effect of toggling between showing and not showing the active
worksheet’s gridlines at each re-execution of this line of code.
Table 8-3 summarizes each possible result of the NOT logical operator.
TABlE 8-3: Truth Table for the OR Logical Operator
cHoosing BETWEEn THis or THAT
This lesson began by mentioning that some code in your macros will need to be purposely bypassed.
Most computer programming languages, VBA included, provide for the flexibility of structuring your
code so that every command does not need to be run in every case. Many times, you will write macros
wherein you will want the program to run certain commands if the user clicks Yes, and alternative
commands if the user clicks No. All of the commands are a part of the macro code, but only one set of them
Among VBA’s arsenal of decision-making commands, the If…Then statement is probably the
simplest and most commonly utilized approach to structure your conditional scenarios. For example,
consider this line of code:
If Weekday(VBA.Date) = 6 Then MsgBox “Have a nice weekend!”, , “Today is Friday!”
You may recall from your experience with Excel’s WEEKDAY worksheet function that to Excel, weekday
number 1 is Sunday, weekday number 2 is Monday, and so on. VBA would look at this line of code
and display the message box only if the line of code is being executed on a Friday because Friday is
weekday number 6. If the weekday is any day other than Friday, VBA bypasses this line of code.
In your prior VBA travels, you might have only seen an If statement with an
accompanying End If statement below it, and you might be wondering why
and how the previous example can be successfully executed without having or
needing an End If statement. The previous example could have been written in
“block” style like this:
If Weekday(VBA.Date) = 6 Then
MsgBox “Have a nice weekend!”, , “Today is Friday!”
When evaluating for a single condition, and the conditional code is one task as
shown in this example, you can write the entire If…Then statement as a single