For…Next - VBScript

For…Next – Iteration Control Structure


The For...Next command in VBScript is used for looping through a sequence of values or executing a block of code multiple times. It provides a structured way to iterate over a range of values, performing specific actions within each iteration.


For counter = start To end [Step increment]
Next [counter]


  • counter: The counter variable used to track the current iteration.
  • start: The starting value of the loop.
  • end: The ending value of the loop.
  • increment: (Optional) The increment value by which the counter is increased in each iteration. Default is 1.

Optional Keyword

  • Next: Specifies the end of the loop. The optional counter parameter can be used after Next to reference the counter variable outside the loop.




Simple Loop

For i = 1 To 10
    MsgBox("Iteration: " & i)

Loop with Increment

For i = 1 To 100 Step 5
    Print("Value: " & i)

Nested Loop

For i = 1 To 3
    For j = 1 To 2
        MsgBox("Outer: " & i & ", Inner: " & j)

Common Issues

  • Off-by-One Errors: Ensure the loop range and increment are correct to avoid missing or extra iterations.
  • Infinite Loops: Avoid setting an increment of 0 or not using the Next keyword, which can lead to endless loops.


For...Next can be combined with other VBScript commands for advanced tasks:

  • With…End With: Use this to group related statements within the loop, providing a more structured code block.
  • Do…Loop: Use this when the loop condition needs to be checked after the statements are executed.
  • Nested Loops: Use multiple For...Next loops to iterate through multidimensional data structures or perform complex calculations.
  • Do…Loop
  • [While…Wend](