Datasheet

Chapter 1: A Quick Introduction to Programming
15
Take a look at why the TryAgain = “No” line is essential to preventing an infinite loop. Going through
the script line by line:
1. This first line starts the loop.
Do
This tells the script engine that you are starting a block of code that will define a loop. The script
engine will expect to find a loop statement somewhere further down in the script. This is similar
to the
If...End If code block because the script engine expects the block to be defined with
beginning and ending statements. The
Do statement on a line all by itself means that the loop will
execute at least once. Even if the
Loop While statement at the end of the block does not result in
a loop around back to the
Do line, the code inside this block will be executed at least one time.
2. Moving on to the second line of code, you initialize the “control” variable. It’s called the “con-
trol” variable because it ultimately controls whether or not the code block loops around again.
You want to initialize this variable to
“No” so that, by default, the loop will not loop around
again. Only if a certain condition is met inside the loop will you set
TryAgain to “Yes” . This is
yet another strategy in an ever-vigilant desire to expect the unexpected.
Do
TryAgain = “No”
3. The next line of code should look familiar. You use the InputBox function to ask the user to
enter a name. You store the return value from the function in the
YourName variable. Whatever
the user types, unless they type nothing, will be stored in this variable. Put another way, the
script receives some external input — and remember that we said input is always unpredictable:
Do
TryAgain = “No”
YourName = InputBox(“Please enter your name:”)
4. In the next part of the code, you test the input. The line If YourName = “ “ Then tests to see if the
user typed in their name (or at least some text). If they typed something in, the code immediately
after the
Else line will execute. If they didn’t type in anything (or if they clicked the Cancel button),
then the
YourName variable will be empty, and the code after the If line will execute instead:
Do
TryAgain = “No”
YourName = InputBox(“Please enter your name:”)
If YourName = “” Then
MsgBox “You must enter your name to continue.”
TryAgain = “Yes”
Else
Greeting = “Hello, “& YourName & “, great to meet you.”
End If
If the user didn’t type anything into the input box, you will display a message informing them
that they have done something you didn’t want them to. You then set the
TryAgain variable
(the control variable) to
“Yes” and send them around the loop once more and ask the users
c01.indd 15c01.indd 15 8/27/07 7:45:22 PM8/27/07 7:45:22 PM