Visual Basic Looping

You've now mastered sequential logic and decision-making logic. This hour's lesson explains how to write programs that contain looping logic. A loop is a set of program instructions that execute repeatedly. Your programming preferences and application dictate how many times the loop must repeat.

Loops play important roles in programs because you'll need to repeat sections of a program to process multiple data values. For example, you may need to calculate a total of past due charges for all past due customers. A loop can read each customer's past-due charge and add that amount to the running total. As you learn more about Visual Basic in subsequent lessons, you will see additional uses for loops.

The highlights of this hour include

·  What a loop is

·  How you code a Do loop

·  Why several Do loop formats exist

·  When to use For

· 
How theExit statements interrupt execution

The Do While Loops

Visual Basic supports several versions of the Do statement. The Do While loop is perhaps the most common looping statement that you'll put in Visual Basic programs. Do While works with comparison expressions just as the If statement does. Therefore, the six comparison operators that you learned about in the previous lesson work as expected here. Rather than control the one-time execution of a single block of code, however, the comparison expression controls the looping statements.

Like the If statement that ends with an End If statement, a loop will always be a multiline statement that includes an obvious beginning and ending of the loop. Here is the format of the Do While loop:

Do While (comparison test)

Block of one or more Visual Basic statements

Loop

The block of code continues looping as long as comparison test is true. Whether you insert one or several lines of code for the block doesn't matter. It's vital, however, that the block of code somehow change a variable used in comparison test. The block of code keeps repeating as long as the Do While loop's comparison test continues to stay true. Eventually, comparison test must become false or your program will enter an infinite loop and the user will have to break the program's execution through an inelegant means, such as pressing the Ctrl+Break key combination.

New Term: An infinite loop is a loop that never terminates.

WARNING: Guard against infinite loops and always make sure your loops can terminate properly. Even if you provide an Exit command button or a File|Exit menu option in your application, the program will often ignore the user's exit command if the program enters an infinite loop.

The Do While loop continues executing a block of Visual Basic statements as long as comparison test is true. As soon as comparison test becomes false, the loop terminates.

The Loops Termination

As long as comparison test is true, the block of code in the body of the loop continues executing. When comparison test becomes false, the loop terminates. After the loop terminates, Visual Basic begins program execution at the statement following the Loop statement because Loop signals the end of the loop. As soon as Do While's comparison test becomes false, the loop terminates and doesn't execute even one more time. The Do While's comparison test appears at the top of the loop. Therefore, if comparison test is false the first time the loop begins, the body of the loop will never execute.
Listing 8.1 contains a section of an event procedure that contains a Do While loop that asks the user for an age. If the user enters an age less than 10 or more than 99, the program beeps at the error and displays another input box asking for the age. The program continues looping, asking for the age, as long as the user enters an age that's out of range.

Listing 8.1. The Do While loop executes as long as comparison test is true.

Dim strAge As String

Dim intAge As Integer

Dim intPress As Integer

` Get the age in a string variable

strAge = InputBox("How old are you?", "Age Ask")

` Check for the Cancel command button

If (strAge = "") Then

End ` Terminates the application

End If

` Cancel was not pressed, so convert Age to integer

` The Val() function converts strings to integers

intAge = Val(strAge)

` Loop if the age is not in the correct range

Do While ((intAge < 10) Or (intAge > 99))

` The user's age is out of range

intPress = MsgBox("Your age must be between " & _

"10 and 99", vbExclamation, "Error!")

strAge = InputBox("How old are you?", "Age Ask")

` Check for the Cancel command button

If (strAge = "") Then

End ` Terminate the program

End If

intAge = Val(strAge

Loop


Figure 8.1 shows the message box error Listing 8.1 displays if the user enters an age value that's less than 10 or more than 99. Listing 8.1 does nothing with MsgBox()'s return value stored in intPress. The user simply presses Enter to close the message box so a check for intPress's value would not help this particular section of code.

NOTE: Listing 8.1 uses the built-in Val() function. Val() accepts a string argument and converts that string to a number (assuming that the string holds the correct digits for a number). The InputBox() function returns a string so the value the user enters into the input box must convert to an integer before you store the value in the integer variable named intAge.


The code contains some redundancy. For example, two lines contain almost the same InputBox() function, and the same check for a Cancel command button press appears twice in the program. There are other looping statements that you'll learn about later in this lesson; those statements can help simplify this code by removing some of the redundancy.

Perhaps the most important thing to note about the Do While loop in Listing 8.1 is that the body of the loop provides a way for comparison test to terminate. The code contains an intAge variable that the body of the loop reassigns each time the loop's block of code executes. Therefore, assuming that the user enters a different value for the age, the loop will test against a different set of comparison values, the comparison test will fail (which would mean that the age is inside the range), and the program will stop looping. If the loop body did nothing with the comparison test variable, the loop would continue forever.

The Do Until Loop

Visual Basic supports several kinds of loops, and you can use the one that best matches your application's requirements. Whereas the Do While loop continues executing the body of the loop as long as the comparison test is true, the Do Until loop executes the body of the loop as long as the comparison test is false. The program's logic at the time of the loop determines which kind of loop works best in a given situation.

Do Until works almost exactly like the Do While loop except that the Do Until loop continues executing the body of the loop until the comparison test is true. Like the Do While, the Do Until is a multiline looping statement that can execute a block of code that's one or more lines long.

Here is the format of the Do Until:

Do Until (comparison test)

Block of one or more Visual Basic statements

Loop

TIP: Remember that the comparison test must be false for the loop to continue.

You can use the Do While or the Do Until for almost any loop. Listing 8.2 contains the age-checking event procedure that contains a Do Until loop. The loop ensures that the age falls between two values. As you can see, comparison test for the Do Until is the opposite of that used in Listing 8.1's Do While loop.

Which Loop Is Best?

Use the loop that makes for the cleanest and clearest comparison test. Sometimes, the logic makes the Do While clearer, whereas other loops seem to work better when you set them up with Do Until. Do Until continues executing a block of Visual Basic statements as long as comparison test is false. As soon as comparison test becomes true (the loop is said to Do a loop until the condition becomes false), the loop terminates and the program continues on the line that follows the closing loop statement.

Listing 8.2. The Do Until loops until comparison test becomes true.

Dim strAge As String

Dim intAge As Integer

Dim intPress As Integer

` Get the age in a string variable

strAge = InputBox("How old are you?", "Age Ask")

` Check for the Cancel command button

If (strAge = "") Then

End ` Terminate the program

End If

` Cancel was not pressed, so convert Age to integer

intAge = Val(strAge)

` Loop if the age is not in the correct range

Do Until ((intAge >= 10) And (intAge <= 99))

` The user's age is out of range

intPress = MsgBox("Your age must be " & _

"between 10 and 99", vbExclamation, "Error!")

strAge = InputBox("How old are you?", "Age Ask")

` Check for the Cancel command button

If (strAge = "") Then

End ` Terminate the program

End If

intAge = Val(strAge)

Loop


The 16th line is the only line that marks the difference between Listing 8.1 and Listing 8.2. The age must now fall within the valid range for the loop to terminate.

NOTE: There is really no technical advantage to using Do While or Do Until. Use whichever one seems to flow the best for any given application.

The Other Do Loops

Another pair of Do loops works almost exactly like the two previous loops. Do-Loop While and Do-Loop Until look very much like their counterparts that you learned earlier. But these new loop formats check their comparison tests at the bottom of the loop rather than at the top.

If a loop begins with a single Do statement, the loop ends with either Loop While or Loop Until. Here is the format of Do-Loop While:

Do

Block of one or more Visual Basic statements

Loop Until (comparison test)

TIP: The hyphen in Do-Loop While serves to remind you that the body of the loop comes before the Loop While statement. The hyphen in the Do-Loop Until performs the same purpose. Some books use ellipses in place of the hyphen, so you may see the statement written as Do...Loop Until.

That Do looks lonely by itself, doesn't it? The purpose of the Do is to signal the beginning of the loop. The loop continues until the Loop Until statement. The comparison test appears at the bottom of the loop if you use the Do-Loop While loop statement. The body of the loop always executes at least once. The body of the loop executes more than once as long as the comparison test stays true. There is a corresponding Do-Loop Until statement that checks for a false condition at the bottom of the loop's body.

Notice that the Do-Loop While loop's comparison test appears at the bottom of the loop instead of at the top of the loop. You'll use the Do-Loop While loop when you want the body of the loop to execute at least one time. Often, by placing comparison test at the bottom of the loop, you can eliminate redundant code that otherwise might be required if you used Do While.

To complete the loop statements, Visual Basic also supports a Do-Loop Until statement. Like the Do-Loop While, the Do-Loop Until statement tests comparison test at the bottom of the loop. Therefore, the body of the loop executes at least once no matter what comparison test turns out to be. The loop continues as long as the comparison test result stays false.

Listing 8.3 contains the age-checking event procedure that's much shorter than the previous versions. comparison test appears at the bottom of the loop, so the extra InputBox() function call is not needed.

Listing 8.3. Using the Do-Loop While to check the comparison at the bottom of the loop.

Dim strAge As String

Dim intAge As Integer

Dim intPress As Integer

Do

strAge = InputBox("How old are you?", "Age Ask")

` Check for the Cancel command button

If (strAge = "") Then

End ` Terminate program

End If

intAge = Val(strAge)

If ((intAge < 10) Or (intAge > 99)) Then

` The user's age is out of range

intPress = MsgBox("Your age must be between " & _

"10 and 99", vbExclamation, "Error!")

End If

Loop While ((intAge < 10) Or (intAge > 99))


The loop begins almost immediately. The loop's body will always execute at least once, so InputBox() appears right inside the loop. By placing the InputBox() function inside the loop, you eliminate the need to put this function in the code twice (once before the loop and once inside the loop, as was necessary using the previous looping statements in Listings 8.1 and 8.2).

NOTE: In this simple application of the looping statements that you've seen here, the Do-Loop While loop required less code than the Do While and Do Until loops. By changing the Do-Loop While's comparison test, a Do Until would also work. These last two loops will not, in every case, produce less code as they do here. The logic of the application determines which loop works best.

The For Loop

The For loop (sometimes called the For-Next loop) also creates a loop. Unlike the Do loops, however, the For loop repeats for a specified number of times. The format of the For loop looks a little more daunting than that of the Do loops, but after you master the format, you'll have little trouble implementing For loops when your code needs to repeat a section of code for a specified number of times.

There isn't one correct loop to use in all situations. The For statement provides the mechanism for the fifth Visual Basic loop block that you'll learn. A For loop always begins with the For statement and ends with the Next statement. Here is the format of the For loop: