Do While/Loop Example:
Counter = 1
Do While Counter < 10
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.
Visual Basic Counting
Counting is accomplished using the For/Next loop.
Example
For I = 1 to 50 Step 2
A = I * 2
Debug.Print A
Next I
In this example, the variable I initializes at 1 and, with each iteration of the For/Next loop, is incremented by 2 (Step). This looping continues until I becomes greater than or equal to its final value (50). If Step is not included, the default Visual Basic Counting value is 1. Negative values of Step are allowed.
You may exit a For/Next loop using an Exit For statement. This will transfer program control to the statement following the Next statement.
.
No comments:
Post a Comment