Datasheet
Chapter 1: A Quick Introduction to Programming
16
for their name again (wherein this time they will hopefully type something into the input box).
If the user did type in his or her name, then you initialize your familiar
Greeting variable. Note
that in this case, you do not change the value of the
TryAgain variable. This is because there is
no need to loop around again because the user has entered a name. The value of
TryAgain is
already equal to
“No” , so there’s no need to change it.
5. In the next line of code, you encounter the end of the loop block. What this Loop line is essen-
tially telling the script engine is “If the
TryAgain variable equals “Yes” at this point, then go
back up to the
Do line and execute all that code over again.” If the user entered his or her name,
then the
TryAgain variable will be equal to “No” . Therefore, the code will not loop again, and
will continue onto the last line:
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
Loop While TryAgain = “Yes”
MsgBox Greeting
MsgBox Greeting
If the user did not enter his or her name, then TryAgain would be equal to “Yes”, which would
mean that the code would again jump back to the
Do line. This is where the reinitialization of
the
TryAgain variable to “No” is essential because if it wasn’t done then there’s no way for
TryAgain to ever equal anything but “Yes”. And if TryAgain always equals “Yes”, then the
loop will keep going around and around forever. This results in total disaster for your script, and
for the user.
Using the For…Next Loop
In this kind of loop, you don’t need to worry about infinite loops because the loop is predefined to
execute only a certain number of times. Here’s a simple (if not very useful) example.
Dim Counter
MsgBox “Let’s count to ten. Ready?”
For Counter = 1 to 10
MsgBox Counter
Next
MsgBox “Wasn’t that fun?”
This loop is similar to the previous loop. The beginning loop block is defined by the For statement, and
the end is defined by the
Next statement. This loop is different because you can predetermine how many
times it will run; in this case, it will go around exactly ten times. The line
For Counter = 1 to 10
essentially tells the script engine, “Execute this block of code as many times as it takes to count from
c01.indd 16c01.indd 16 8/27/07 7:45:23 PM8/27/07 7:45:23 PM