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 ]  


counterRequired in the For statement. Numeric variable. The control variable for the loop. For more information, see Counter Argument later in this topic.
datatypeOptional. Data type of counter. For more information, see Counter Argument later in this topic.
startRequired. Numeric expression. The initial value of counter.
endRequired. Numeric expression. The final value of counter.
stepOptional. Numeric expression. The amount by which counter is incremented each time through the loop.
statementsOptional. One or more statements between For and Next that run the specified number of times.
Continue ForOptional. Transfers control to the next loop iteration.
Exit ForOptional. Transfers control out of the For loop.
NextRequired. Terminates the definition of the For loop.


The To keyword is used in this statement to specify the range for the counter. You can also use this keyword in the Select...Case Statement and in array declarations. For more information about array declarations, see Dim Statement.

Simple Examples

You use a For...Next structure when you want to repeat a set of statements a set number of times.

In the following example, the index variable starts with a value of 1 and is incremented with each iteration of the loop, ending after the value of index reaches 5.

For index As Integer = 1 To 5
    Debug.Write(index.ToString & " ")
' Output: 1 2 3 4 5

In the following example, the number variable starts at 2 and is reduced by 0.25 on each iteration of the loop, ending after the value of number reaches 0. The Step argument of -.25 reduces the value by 0.25 on each iteration of the loop.

For number As Double = 2 To 0 Step -0.25
    Debug.Write(number.ToString & " ")
' Output: 2 1.75 1.5 1.25 1 0.75 0.5 0.25 0 


A While...End While Statement or Do...Loop Statement works well when you don't know in advance how many times 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.

Nesting Loops

You can nest For loops by putting one loop within another. 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(" ")
    Next indexB

    ' Display the line.
Next indexA
' Output:
'  20 17 14 11 8 5 2
'  20 17 14 11 8 5 2
'  20 17 14 11 8 5 2

When nesting loops, 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.

Exit For and Continue For

The Exit For statement immediately exits the ForNext loop and transfers control to the statement that follows the Next statement.

The Continue For statement transfers control immediately to the next iteration of the loop. For more information, see Continue Statement.

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
' Output: 1 2 3 4 9 10

You can put any number of Exit For statements in a ForNext loop. When used within nested ForNextloops, 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. An erroneous value or a termination request might create this condition.

  • A Try...Catch...Finally statement catches an exception. You might use Exit For at the end of the Finally block.

  • You have 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.

Technical Implementation

When a For...Next loop starts, Visual Basic evaluates start, end, and step. Visual Basic evaluates these values only at this time and then assigns start to counter. Before the statement block runs, Visual Basic 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 that follows 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 Forstatement. 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 doesn't 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.

If you change the value of counter while inside a loop, your code might be more difficult to read and debug. Changing the value of start, end, or step doesn't affect the iteration values that were determined when the loop was first entered.

If you nest loops, the compiler signals an error if it encounters the Next statement of an outer nesting level before the Next statement of an inner level. However, the compiler can detect this overlapping error only if you specify counter in every Next statement.

Step Argument

The value of step can be either positive or negative. This parameter determines loop processing according to the following table:

Step valueLoop executes if
Positive or zerocounter <= end
Negativecounter >= end

The default value of step is 1.

Counter Argument

The following table indicates whether counter defines a new local variable that’s scoped to the entire For…Nextloop. This determination depends on whether datatype is present and whether counter is already defined.

Is datatypepresent?Is counteralready defined?Result (whether counter defines a new local variable that’s scoped to the entire For...Next loop)
NoYesNo, because counter is already defined. If the scope of counter isn't local to the procedure, a compile-time warning occurs.
NoNoYes. The data type is inferred from the start, end, and step expressions. For information about type inference, see Option Infer Statement and Local Type Inference.
YesYesYes, but only if the existing counter variable is defined outside the procedure. That variable remains separate. If the scope of the existing counter variable is local to the procedure, a compile-time error occurs.

The data type of counter determines the type of the iteration, which must be one of the following types:

  • A Byte, SByte, UShort, Short, UInteger, Integer, ULong, Long, Decimal, Single, or Double.

  • An enumeration that you declare by using an Enum Statement.

  • An Object.

  • A type T that has the following operators, where B is a type that can be used in a Booleanexpression.

    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

You can optionally specify the counter variable in the Next statement. This syntax improves the readability of your program, especially if you have nested For loops. You must specify the variable that appears in the corresponding For statement.

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, you might have to define the CType conversion operator to convert the types of start, end, or step to the type of counter.

+ Recent posts