182 Part II Programming Fundamentals
The syntax for a For... Next loop looks like this:
For variable = start To end
statements to be repeated
Next [variable]
In this syntax statement, For, To, and Next are required keywords, as is the equal to
operator (=). You replace variable with the name of a numeric variable that keeps track
of the current loop count (the variable after Next is optional), and you replace start and
end with numeric values representing the starting and stopping points for the loop. (Note
that you must declare variable before it’s used in the For... Next statement and that you
don’t type in the brackets, which I include to indicate an optional item .) The line or lines
between the For and Next statements are the instructions that are repeated each time
the loop is executed.
For example, the following For... Next loop sounds four beeps in rapid succession from
the computer’s speaker (although the result might be difficult to hear):
Dim i As Integer
For i = 1 To 4
Beep()
Next i
This loop is the functional equivalent of writing the Beep statement four times in a procedure.
The compiler treats it the same as:
Beep()
Beep()
Beep()
Beep()
The variable used in the loop is i, a single letter that, by convention, stands for the first
integer counter in a For... Next loop and is declared as an Integer type. Each time the
loop is executed, the counter variable is incremented by 1. (The first time through the
loop, the variable contains a value of 1, the value of start; the last time through, it contains
a value of 4, the value of end .) As you’ll see in the following examples, you can use this
counter variable to great advantage in your loops.
Tip In loops that use counter variables, the usual practice is to use the Integer type for the
variable declaration, as I did previously. However, you will get similar performance in Visual Basic
2010 if you declare the counter variable as type Long or Decimal.