TechnologyUK - Programming (VB6) Logo

Loops

A loop is a programming construct that is used to carry out an action repeatedly, and Visual Basic provides a number of loop constructs, which are described below.



The Do ... While Loop

This construct examines a condition and executes the statement (or statements) within the loop if the condition is true, after which it will examine the condition once more. As long as the condition remains true, the statement will continue to be executed and the condition re-examined. If the condition is false when the loop begins, the statement will never execute. Otherwise, once the condition becomes false, the program will exit the loop and the statement will not be executed again. Care must be taken to ensure that a false condition can exist at some point, or the program will be stuck in a loop it cannot break out of. The construction of the Do ... While loop is as follows:

Do While Condition
    Statement(s)

Loop



The Do ... Loop ... While Statement

The Do ... Loop ... While construct is similar to the Do ... While loop, except that the statement(s) within the loop will always execute at least once, because the condition is not tested until the end of the loop. The construction of the Do ... Loop ... While loop is as follows:

Do
    Statement(s)
Loop While Condition



The Do ... Until ... Loop Statement

The Do ... Until ... Loop construct is virtually identical to the Do ... While loop, except that the statement(s) within the loop are executed only while the condition is false. The construction of the Do ... Until ... Loop statement is as follows:

Do Until Condition
    Statement(s)

Loop



The Do ... Loop ... Until Statement

The Do ... Loop ... Until statement is virtually identical to the Do ... Loop ... While statement, except that the statement(s) within the loop are executed only while the condition is false. The construction of the Do ... Loop ... Until statement is as follows:

Do
    Statement(s)
Loop Until Condition



Counting Loops

Counting loops are used to execute a statement (or series of statements) a specific number of times.



The For ... To ... Next Loop

The construct used here is as follows:

For Counter = Start To End
    Statement(s)

Next

Execution of the loop begins with Counter set to the value specified by Start, and examines whether this value is greater than the value specified by End. If not, any statements within the loop are executed, and the value of Counter is incremented by 1. This process continues until the value of Counter becomes equal to the value of End, at which point execution of the loop stops. A variation on the counting loop uses the Step keyword to set the value by which Counter is incremented each time through the loop by a specified value, as shown below.

For Counter = Start To End Step Increment
    Statement(s)

Next Counter