Visual Basic/Loops< Visual Basic
Loops are control structures used to repeat a given section of code a certain number of times or until a particular condition is met.
Visual Basic has three main types of loops: for..next loops, do loops and while loops.
Note: 'Debug' may be a reserved word in Visual Basic, and this may cause the code samples shown here to fail for some versions of Visual Basic.
The syntax of a For..Next loop has three components: a counter, a range, and a step. A basic for..next loop appears as follows:
For X = 1 To 100 Step 2 Debug.Print X Next X
In this example, X is the counter, "1 to 100" is the range, and "2" is the step.
The variable reference in the Next part of the statement is optional and it is common practice to leave this out. There is no ambiguity in doing this if code is correctly indented.
When a For..Next loop is initialized, the counter is set to the first number in the range; in this case, X is set to 1. The program then executes any code between the for and next statements normally. Upon reaching the next statement, the program returns to the for statement and increases the value of the counter by the step. In this instance, X will be increased to 3 on the second iteration, 5 on the third, etc.
To change the amount by which the counter variable increases on each iteration, simply change the value of the step. For example, if you use a step 3, X will increase from 1 to 4, then to 7, 10, 13, and so on. When the step is not explicitly stated, 1 is used by default. (Note that the step can be a negative value. For instance, for X = 100 to 1 step -1 would decrease the value of X from 100 to 99 to 98, etc.)
When X reaches the end of the range in the range (100 in the example above), the loop will cease to execute, and the program will continue to the code beyond the next statement.
It is possible to edit the value of the counter variable within a for..next loop, although this is generally considered bad programming practice:
For X = 1 To 100 Step 1 Debug.Print X X = 7 Next
While you may on rare occasions find good reasons to edit the counter in this manner, the example above illustrates one potential pitfall:
Because X is set to 7 at the end of every iteration, this code creates an infinite loop. To avoid this and other unexpected behavior, use extreme caution when editing the counter variable!
It is not required by the compiler that you specify the name of the loop variable in the Next statement but it will be checked by the compiler if you do, so it is a small help in writing correct programs.
For loop on listEdit
Another very common situation is the need for a loop which enumerates every element of a list. The following sample code shows you how to do this:
Dim v As Variant For Each v In list Debug.Print v Next
The list is commonly a Collection or Array, but can be any other object that implements an enumerator. Note that the iterating variable has to be either a Variant, Object or class that matches the type of elements in the list.
Do loops are a bit more flexible than For loops, but should generally only be used when necessary. Do loops come in the following formats:
- Do while
- Do until
- Loop while
- Loop until
While loops (both do while and loop while) will continue to execute as long as a certain conditional is true. An Until loop will loop as long as a certain condition is false, on the other hand. The only difference between putting either While or Until in the Do section or the Loop section, is that Do checks when the loop starts, and Loop checks when the loop ends. An example of a basic loop is as follows:
Do Debug.Print "hello" x = x + 1 Loop Until x = 10
This loop will print hello several times, depending on the initial value of x. As you may have noticed, Do loops have no built in counters. However, they may be made manually as shown above. In this case, I chose x as my counter variable, and every time the loop execute, x increase itself by one. When X reaches 10, the loop will cease to execute. The advantage of Do loops is that you may exit at any time whenever any certain conditional is met. You may have it loop as long as a certain variable is false, or true, or as long as a variable remains in a certain range.
Endless loop: Do..LoopEdit
The endless loop is a loop which never ends and the statements inside are repeated forever. Never is meant as a relative term here - if the computer is switched off then even endless loops will end very abruptly.
Do Do_Something Loop
In Visual Basic you cannot label the loop but you can of course place a label just before it, inside it or just after it if you wish.
Loop with condition at the beginning: Do While..LoopEdit
This loop has a condition at the beginning. The statements are repeated as long as the condition is met. If the condition is not met at the very beginning then the statements inside the loop are never executed.
Do While X <= 5 X = Calculate_Something Loop
Loop with condition at the end: Do..Loop UntilEdit
This loop has a condition at the end and the statements are repeated until the condition is met. Since the check is at the end the statements are at least executed once.
Do X = Calculate_Something Loop Until X > 5
Loop with condition in the middle:Do..Exit Do..LoopEdit
Sometimes you need to first make a calculation and exit the loop when a certain criterion is met. However when the criterion is not met there is something else to be done. Hence you need a loop where the exit condition is in the middle.
Do X = Calculate_Something If X > 10 then Exit Do End If Do_Something (X) Loop
In Visual Basic you can also have more than one exit statement. You cannot exit named outer loops using Exit Do because Visual Basic does not provide named loops; you can of course use Goto instead to jump to a label that follows the outer loop.
While loops are similar to Do loops except that the tested condition always appears at the top of the loop. If on the first entry into the loop block the condition is false, the contents of the loop are never executed. The condition is retested before every loop iteration.
An example of a While loop is as follows:
price = 2 While price < 64 Debug.Print "Price = " & price price = price ^ 2 Wend Debug.Print "Price = " & price & ": Too much for the market to bear!"
The While loop will run until the condition tests false - or until an "Exit While" statement is encountered.
A nested loop is any type of loop inside an already existing loop. They can involve any type of loop. For this, we will use For loops. It is important to remember that the inner loop will execute its normal amount multiplied by how many times the outer loop runs. For example:
For i = 1 To 10 For j = 1 To 2 Debug.Print "hi" Next Next
This will print the word 'hi' twenty times. Upon the first pass of the i loop, it will run the j loop twice. Then on the second pass of the i loop, it will run the j loop another two times, and so on.
|Previous: Branching||Contents||Next: Strings|