2. The Visual Basic Language
Visual Basic Looping
- Looping is done with the Do/Loop format.
Loops are used for operations are to be repeated some number of times.
The loop repeats until some specified condition at the beginning or end
of the loop is met.
- Do While/Loop Example:
Counter = 1
Do While Counter <= 1000
Debug.Print Counter
Counter = Counter + 1
Loop
This loop repeats as long as (While) the variable Counter is
less than or equal to 1000. Note a Do While/Loop structure will not
execute even once if the While condition is violated (False) the first
time through. Also note the Debug.Print statement.
What this does is print the value Counter in the Visual Basic Debug
window. We'll learn more about this window later in the course.
- Do Until/Loop Example:
Counter = 1
Do Until Counter > 1000
Debug.Print Counter
Counter = Counter + 1
Loop
This loop repeats Until the Counter variable exceeds 1000.
Note a Do Until/Loop structure will not be entered if the Until
condition is already True on the first encounter.
- Do/Loop While Example:
Sum = 1
Do
Debug.Print Sum
Sum = Sum + 3
Loop While Sum <= 50
This loop repeats While the Variable Sum is less than or equal
to 50. Note, since the While check is at the end of the loop, a Do/Loop
While structure is always executed at least once.
- Do/Loop Until Example:
Sum = 1
Do
Debug.Print Sum
Sum = Sum + 3
Loop Until Sum > 50
This loop repeats Until Sum is greater than 50. And, like the previous
example, a Do/Loop Until structure always executes at least once.
- Make sure you can always get out of a loop! Infinite loops are
never nice. If you get into one, try Ctrl+Break. That sometimes
works - other times the only way out is rebooting your machine!
- The statement Exit Do will get you out of a loop and
transfer program control to the statement following the Loop statement.
Counter Hit
This Homepage is special brought to you by CK Tan