Datasheet

Chapter 1: A Quick Introduction to Programming
14
Looping
Branching allows you to tell the script to execute some lines of code, but not others. Looping , on the other
hand, allows you to tell the script to execute some lines of code over and over again. This is particularly
useful in two situations:
When you want to repeat a block of code until a condition is True or False
When you want to repeat a block of code a finite number of times
There are many different looping constructs, but this section focuses on only two of them:
The basic Do...Loop While loop
The basic For...Next loop
Using the Do…Loop While Loop
This section takes a look at the Do...Loop While construct and how it can be used to repeatedly
execute a block of code until a certain condition is met. Take a look at the following modification of
the example script:
Dim Greeting
Dim YourName
Dim TryAgain
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
Notice the block of code that starts with the word Do and ends with the line that starts with the word Loop .
The indentation should make this code block easy to identify. This is the definition of the loop. The code
inside the loop will keep being executed until at the end of the loop the TryAgain variable equals “No” .
The
TryAgain variable controls the loop. The loop starts at the word Do . At the end of the loop, if the
TryAgain variable equals “Yes” , then all the code, starting at the word Do , will execute again.
Notice that the top of the loop initializes the
TryAgain variable to “No” . It is absolutely essential that
this initialization take place inside the loop (that is, between the Do and Loop statements). This way, the
variable is reinitialized every time a loop occurs. If you didn’t do this, you would end up with what’s
called an infinite loop. They are always bad. At best, the user is going to have to exit out of the program
in an untimely (and inelegant) way because, as the name suggests, the loop is infinite. At worse, it can
crash the system. You want neither and you want to try to avoid both in your code.
c01.indd 14c01.indd 14 8/27/07 7:45:22 PM8/27/07 7:45:22 PM