At times, there will be certain parts of the code you would like to repeat itself over
and over, sometimes changing between runs. These are called loops. There are
two types of loops, For...Next loops and Do loops. In both loops, the variables use the values they
had from the last run of the loop.
For…Next loops run code over and over, changing a given variable between runs with a given
starting point and ending point for that variable. When that variable finds
its ending
point, then it doesn't run the code again; it just continues to run the commands after the
loop. For Variable = StartValue To EndValue Step Number.
This will start Variable at StartValue and run the loop with
every number between it and EndValue skipping Number of numbers.
If the Step part is left out, then the script will think Step 1. Step is the number
added to i between loops (or subtracted if it is a negative step like -1 or -5 or
something like that). You close a For…Next loop with the Next keyword. Example:
For i = 5
To 200 Step
5
'This will run i from 5 to 10 to 15 to 20, etc.
For y = 200 To 5 Step -1
'This will run y from 200 to 199 to 198, etc.
Next
Next
Another type of loop is a DO loop. This loop tests for a rule between loops.
It tests this rule based on two words Until or while. The rule is tested on
the Do (beginning) or the While (or end of the loop block's range of code). Until
will stop the loop if the rule is true, in other words, UNTIL it is true. While will
stop the look when the rule becomes false, in other words, only keep looping WHILE it is
true. Example:
A = 10
B = 0
Do While A <> 1 'This will take
9 loops to do, because the first test it's done after one loop but before the first so the
when it = 10 it is not counted.
A = A - 1
Do
B = B +1
Loop Until B = 3
'this will take 3 loop because 0 want see the test, it's become 1 by now.
Loop
By: Matthew Holder