192 Part II Programming Fundamentals
Writing Do Loops
As an alternative to a For... Next loop, you can write a Do loop that executes a group of
statements until a certain condition is True. Do loops are valuable because often you can’t
know in advance how many times a loop should repeat. For example, you might want to let
the user enter names in a database until the user types the word Done in an input box. In
that case, you can use a Do loop to cycle indefinitely until the Done text string is entered.
A Do loop has several formats, depending on where and how the loop condition is evaluated.
The most common syntax is:
Do While condition
block of statements to be executed
Loop
For example, the following Do loop prompts the user for input and displays that input in
a text box until the word Done is typed in the input box:
Dim InpName As String
Do While InpName <> "Done"
InpName = InputBox("Enter your name or type Done to quit.")
If InpName <> "Done" Then TextBox1.Text = InpName
Loop
The conditional statement in this loop is InpName <> "Done", which the Visual Basic
compiler translates to mean “loop so long as the InpName variable doesn’t contain the
exact word ‘Done’ .” This brings up an interesting fact about Do loops: If the condition at
the top of the loop isn’t True when the Do statement is first evaluated, the Do loop is never
executed. Here, if the InpName string variable did contain the “Done” value before the loop
started (perhaps from an earlier assignment in the event procedure), Visual Basic would skip
the loop altogether and continue with the line below the Loop keyword.
If you always want the loop to run at least once in a program, put the conditional test at the
bottom of the loop. For example, the loop:
Dim InpName As String
Do
InpName = InputBox("Enter your name or type Done to quit.")
If InpName <> "Done" Then TextBox1.Text = InpName
Loop While InpName <> "Done"
is essentially the same as the previous Do loop, but here the loop condition is tested after
a name is received from the InputBox function. This has the advantage of updating the
InpName variable before the conditional test in the loop so that a preexisting Done value
won’t cause the loop to be skipped. Testing the loop condition at the bottom ensures that
your loop is executed at least once, but often it forces you to add a few extra statements to
process the data.