For…Next - VBScript
For…Next – Iteration Control Structure
Overview
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.
Syntax
For counter = start To end [Step increment]
[statements]
Next [counter]
Parameters
- 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 afterNext
to reference the counter variable outside the loop.
Options/Flags
None
Examples
Simple Loop
For i = 1 To 10
MsgBox("Iteration: " & i)
Next
Loop with Increment
For i = 1 To 100 Step 5
Print("Value: " & i)
Next
Nested Loop
For i = 1 To 3
For j = 1 To 2
MsgBox("Outer: " & i & ", Inner: " & j)
Next
Next
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.
Integration
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.
Related Commands
- Do…Loop
- [While…Wend](https://docs.microsoft.com/en-us/previous-versions/visualstudio/visual-basic/visual-basic-6.0/language-reference/while-w