Visual Basic includes three major types of loops:
For Each...Next, and
Do...Loop. Just as conditions allow you to break up the sequential monotony of your code through branches, loops add to the usefulness of your code by letting you repeat a specific block of logic a fixed or variable number of times.
For...Next loop uses a numeric counter that increments from a starting value to an ending value, processing the code within the loop once for each incremented value.
Dim whichMonth As Integer For whichMonth = 1 To 12 ProcessMonthlyData(whichMonth) Next whichMonth
This sample loops 12 times (
1 To 12), once for each month. You can specify any starting and ending values you wish; this range can also be specified using variables or functions that return numeric values. Once the starting and ending values are obtained, they are not recalculated each time through the loop, even if a function call is used to obtain one or both limits.
' ----- Month(Today) returns the numeric month ' for the current date. For whichMonth = 1 To Month(Today) ProcessMonthlyData(whichMonth) Next whichMonth
Normally, the loop increments by one (
1) each time through. You can alter this default by attaching a
Step clause to the end of the
For statement line:
For countDown = 60 To 0 Step −1 ... Next countDown
One additional syntax variation allows you to declare the loop counter variable within the statement itself. Such variables are available only within the loop, and cease to ...