For...Next Statement (Visual Basic)
Repeats a group of statements a specified number of times.
For counter [ As datatype ] = start To end [ Step step ]
[ statements ]
[ Continue For ]
[ statements ]
[ Exit For ]
[ statements ]
Next [ counter ]
Parts
Part |
Description |
counter |
Required in the For statement. Numeric variable. The control variable for the loop. |
datatype |
Required if counter is not already declared. Data type of counter. |
start |
Required. Numeric expression. The initial value of counter. |
end |
Required. Numeric expression. The final value of counter. |
step |
Optional. Numeric expression. The amount by which counter is incremented each time through the loop. |
statements |
Optional. One or more statements between For and Next that run the specified number of times. |
Continue For |
Optional. Transfers control to the next loop iteration. |
Exit For |
Optional. Transfers control out of the For loop. |
Next |
Required. Terminates the definition of the For loop. |
Poznámka
The To keyword is used here to specify the range for the counter. It is also used to specify a range of values in the Select...Case Statement (Visual Basic) and in array declarations. For more information about array declarations, see Dim Statement (Visual Basic).
Remarks
Use a For...Next structure when you want to repeat a set of statements a set number of times.
When a For...Next loop starts, Visual Basic evaluates start, end, and step. This is the only time it evaluates these values. It then assigns start to counter. Before it runs the statement block, it compares counter to end. If counter is already larger than the end value (or smaller if step is negative), the For loop ends and control passes to the statement following the Next statement. Otherwise the statement block runs.
Each time Visual Basic encounters the Next statement, it increments counter by step and returns to the For statement. Again it compares counter to end, and again it either runs the block or exits the loop, depending on the result. This process continues until counter passes end or an Exit For statement is encountered.
The loop does not stop until counter has passed end. If counter is equal to end, the loop continues. The comparison that determines whether to run the block is counter <= end if step is positive and counter >= end if step is negative.
Changing the value of counter while inside a loop can make it more difficult to read and debug your code. Changing the value of start, end, or step does not affect the iteration values determined when the loop was first entered.
Tip
A While...End While Statement (Visual Basic) or Do...Loop Statement (Visual Basic) works well when you do not know in advance how many times you have to run the statements in the loop. However, when you expect to run the loop a specific number of times, a For...Next loop is a better choice. You determine the number of iterations when you first enter the loop.
Step Argument
The value of step can be either positive or negative. It determines loop processing as follows:
Step value |
Loop executes if |
Positive or zero |
counter <= end |
Negative |
counter >= end |
If not specified, step defaults to 1.
Counter Argument
If counter has not been declared outside this loop, you must declare it in the For statement. In this case, the scope of counter is the body of the loop. However, you cannot declare counter both outside and inside the loop.
You can optionally specify counter in the Next statement. This improves the readability of your program, especially if you have nested For loops. You must specify the same variable as the one that appears in the corresponding For statement.
The data type of counter determines the type of the iteration, and must be one of the following:
A Byte, SByte, UShort, Short, UInteger, Integer, ULong, Long, Decimal, Single, or Double.
An enumeration that you declare by using an Enum Statement (Visual Basic).
An Object.
A type T that has the following operators, where B is a type that can be used in a Boolean expression.
Public Shared Operator >= (op1 As T, op2 As T) As B
Public Shared Operator <= (op1 As T, op2 As T) As B
Public Shared Operator - (op1 As T, op2 As T) As T
Public Shared Operator + (op1 As T, op2 As T) As T
The start, end, and step expressions can evaluate to any data type that widens to the type of counter. If you use a user-defined type for counter, this means you might have to define the CType conversion operator to convert the types of start, end, or step to the type of counter.
Nesting Loops
You can nest For loops by putting one loop within another. However, each loop must have a unique counter variable.
You can also nest different kinds control structures within each other. For more information, see Nested Control Structures (Visual Basic).
If a Next statement of an outer nesting level is encountered before the Next of an inner level, the compiler signals an error. However, the compiler can detect this overlapping error only if you specify counter in every Next statement.
Exit For
The Exit Statement (Visual Basic) immediately exits the For…Next loop and transfers control to the statement following the Next statement.
You can put any number of Exit For statements in a For…Next loop. When used within nested For…Next loops, Exit For exits the innermost loop and transfers control to the next higher level of nesting.
Exit For is often used after you evaluate some condition, for example in an If...Then...Else structure. You might want to use Exit For for the following conditions:
Continuing to iterate is unnecessary or impossible. This might be caused by an erroneous value or a termination request.
An exception is caught in a Try...Catch...Finally. You might use Exit For at the end of the Finally block.
There an endless loop, which is a loop that could run a large or even infinite number of times. If you detect such a condition, you can use Exit For to escape the loop. For more information, see Do...Loop Statement (Visual Basic).
The Continue For statement transfers control immediately to the next iteration of the loop. For more information, see Continue Statement (Visual Basic).
Example
The following example illustrates the use of the For…Next statement. A loop counter variable is incremented with each iteration of the loop. The step argument is not specified, so it defaults to 1.
For index As Integer = 1 To 5
Debug.Write(index.ToString & " ")
Next
Debug.WriteLine("")
' Output: 1 2 3 4 5
In the following example, the counter and step arguments are Double floating point numbers.
For number As Double = 2 To 0 Step -0.25
Debug.Write(number.ToString & " ")
Next
Debug.WriteLine("")
' Output: 2 1.75 1.5 1.25 1 0.75 0.5 0.25 0
The following example demonstrates nested For...Next structures that have different step values. The outer loop creates a string for every iteration of the loop. The inner loop decrements a loop counter variable for every iteration of the loop.
For indexA = 1 To 3
' Create a new StringBuilder, which is used
' to efficiently build strings.
Dim sb As New System.Text.StringBuilder()
' Append to the StringBuilder every third number
' from 20 to 1 descending.
For indexB = 20 To 1 Step -3
sb.Append(indexB.ToString)
sb.Append(" ")
Next indexB
' Display the line.
Debug.WriteLine(sb.ToString)
Next indexA
' Output:
' 20 17 14 11 8 5 2
' 20 17 14 11 8 5 2
' 20 17 14 11 8 5 2
The following example removes all elements from a generic list. Instead of a For Each...Next Statement (Visual Basic), a For...Next statement that iterates in descending order is used. This is because the removeAt method causes elements after the removed element to have a lower index value.
Dim lst As New List(Of Integer) From {10, 20, 30, 40}
For index As Integer = lst.Count - 1 To 0 Step -1
lst.RemoveAt(index)
Next
Debug.WriteLine(lst.Count.ToString)
' Output: 0
The following example illustrates the use of the Continue For and Exit For statements.
For index As Integer = 1 To 100000
' If index is between 5 and 7, continue
' with the next iteration.
If index >= 5 And index <= 8 Then
Continue For
End If
' Display the index.
Debug.Write(index.ToString & " ")
' If index is 10, exit the loop.
If index = 10 Then
Exit For
End If
Next
Debug.WriteLine("")
' Output: 1 2 3 4 9 10
The following example iterates through an enumeration that is declared by using an Enum Statement (Visual Basic).
Public Enum Mammals
Buffalo
Gazelle
Mongoose
Rhinocerous
Whale
End Enum
Public Sub ListSomeMammals()
For mammal As Mammals = Mammals.Gazelle To Mammals.Rhinocerous
Debug.Write(mammal.ToString & " ")
Next
Debug.WriteLine("")
' Output: Gazelle Mongoose Rhinocerous
End Sub
In the following example, the statement parameters use a class that has operator overloads for the +, -, >=, and <= operators.
Private Class Distance
Public Property Number() As Double
Public Sub New(ByVal number As Double)
Me.Number = number
End Sub
' Define operator overloads to support For...Next statements.
Public Shared Operator +(ByVal op1 As Distance, ByVal op2 As Distance) As Distance
Return New Distance(op1.Number + op2.Number)
End Operator
Public Shared Operator -(ByVal op1 As Distance, ByVal op2 As Distance) As Distance
Return New Distance(op1.Number - op2.Number)
End Operator
Public Shared Operator >=(ByVal op1 As Distance, ByVal op2 As Distance) As Boolean
Return (op1.Number >= op2.Number)
End Operator
Public Shared Operator <=(ByVal op1 As Distance, ByVal op2 As Distance) As Boolean
Return (op1.Number <= op2.Number)
End Operator
End Class
Public Sub ListDistances()
Dim distFrom As New Distance(10)
Dim distTo As New Distance(25)
Dim distStep As New Distance(4)
For dist As Distance = distFrom To distTo Step distStep
Debug.Write(dist.Number.ToString & " ")
Next
Debug.WriteLine("")
' Output: 10 14 18 22
End Sub
See Also
Tasks
How to: Improve the Performance of a Loop (Visual Basic)
Reference
While...End While Statement (Visual Basic)
Do...Loop Statement (Visual Basic)
For Each...Next Statement (Visual Basic)
Concepts
Loop Structures (Visual Basic)
Nested Control Structures (Visual Basic)
Change History
Date |
History |
Reason |
December 2010 |
Reorganized the Remarks section and added examples. |
Information enhancement. |