Chapter 10: VBA Programming Fundamentals
401
Running the BeepWarning procedure is easy. Simply type BeepWarning into the Immediate
window and press Enter. You might hear five beeps or only a continuous beep because the interval
between beeps is short.
Figure 10.10, earlier in this chapter, also shows the VBA code for this subprocedure.
Cross-Reference
You’ll see many more examples of using the Immediate window in Chapter 14.
Understanding VBA Branching Constructs
The real power of any programming language is its capability to make a decision based on a condi-
tion that might be different each time the user works with the application. VBA provides two ways
for a procedure to execute code conditionally: branching and looping.
Branching
Often, a program performs different tasks based on some value. If the condition is True, the code
performs one action. If the condition is False, the code performs a different action. An applica-
tion’s capability to look at a value and, based on that value, decide which code to run is known as
branching (or conditional processing).
The procedure is similar to walking down a road and coming to a fork in the road; you can go to
the left or to the right. If a sign at the fork points left for home and right for work, you can decide
which way to go. If you need to go to work, you go to the right; if you need to go home, you go to
the left. In the same way, a program looks at the value of some variable and decides which set of
code should be processed.
VBA offers two sets of conditional processing statements:
l If...Then...Else...End If
l (^) Select Case...End Select
The If...Then...Else...End If construct
The If...Then...End If and If...Then...Else...End If construct checks a condition
and, based on the evaluation, perform an action. The condition must evaluate to a Boolean value
(True or False). If the condition is True, the program moves to the line following the If state-
ment. If the condition is False, the program skips to the statement following the Else statement,
if present, or the End If statement if there is no Else clause.
In Figure 10.18, the code examines the value of the ContactType, and if the value is “Buyer”,
the Customer page is made visible; otherwise, the Customer page is made invisible.