Microsoft Office Tutorials and References
In Depth Information
If…Then…Else
line of code as you saw. Some programmers prefer a single If line for their
onecondition evaluations, and other programmers prefer the block style. It comes
down to a personal preference and whatever feels more intuitive to you.
if…Then…Else
More often than not, your evaluations will involve two or more conditions instead of just one. When
you have two conditions and each has its own set of tasks to carry out, you need to separate the two
conditions with the Else statement in a block If structure.
Expanding on the previous example, say you want to display a message box if today is Friday, but a
different message box if today is not Friday. Here is the format you would use in your macro:
If Weekday(VBA.Date) = 6 Then
MsgBox “Have a nice weekend!”, , “Today is Friday!”
Else
MsgBox “Alas, today is not Friday.”, , “Not Friday yet!”
End If
Notice that the Else statement stands alone on its own dedicated line, separating the two conditions’
respective commands. Only one condition can possibly evaluate to True in this example, because today
is either Friday or it is some day other than Friday. This block of code is designed to always be executed
such that only one of the message box commands would appear, but never both during the same run.
Here’s a design tip to speed up your programs. In a block If structure with
multiple conditions, VBA will look at each condition in turn, and basically stop at, and
execute the conditional code for, the first condition that is found to evaluate to
True. With two or three conditions, it might not be a big deal in which order you
set your conditions in the If structure. But sometimes you will be programming
for multiple conditions, and the point is, you will want VBA to execute its process
as efficiently as possible. A good habit to get into is to design your If structures
by setting the first condition to be the one that’s most likely to be the case. That
way, most of the time, the first condition will be the True condition and VBA will
not waste time evaluating the alternative unlikelier scenarios. With this in mind,
the previous example is a good opportunity to show how to make your code run
faster. You can see that the first condition dealt with the current weekday being
Friday. If you think about it, there is only one chance in seven that that will be the
case. Mostly, the macro will be run on one of the other days of the week. A better
way to write the If code is to consider which condition will be True more often
than the other condition(s). Six out of seven days will not be a Friday, so that
condition should be placed first, as shown in this example:
If Weekday(VBA.Date) <> 6 Then
MsgBox “Alas, today is not Friday.”, , “Not Friday yet!”
Else
MsgBox “Have a nice weekend!”, , “Today is Friday!”
End If
 
Search JabSto ::




Custom Search