For - Next
This lets you repeat something a fixed number of times.
This can be used when you know in advance how many times you want to loop.
Positive Increment
This example will loop 5 times.
Public Sub ForNext1()
Dim icount As Integer
For icount = 1 To 5 Step 1
'do something
Next icount
End Sub
The Step 1 is optional because the default is plus 1.
Appending the variable name after the Next statement is optional, but it should be included for completeness.
Public Sub ForNext2()
Dim icount As Integer
For icount = 1 To 5
'do something
Next
End Sub
Negative Increment
Here is an example using a negative increment.
Public Sub ForNext3()
Dim icount As Integer
For icount = 5 To 1 Step -1
'do something
Next icount
End Sub
Decimal Increment
Here is an example using a decimal increment.
Public Sub ForNext4()
Dim dbcount As Single
For dbcount = 1 To 3 Step 0.3
'do something
Next dbcount
End Sub
Nested Loops
You can nest loops inside one another.
The outside loops through 5 times and for each loop, the inside loops 3 times.
Public Sub ForNext5()
Dim iouter As Integer
Dim inner As Integer
For iouter = 1 To 5 Step 1
For inner = 2 To 4 Step 1
'do something
Next inner
Next iouter
End Sub
Nested Loops - Combined Next Statements
You can also combine Next statements onto one line, although this is not recommended.
Always use separate lines for your Next statements. It makes your code much easier to read.
Public Sub ForNext6()
Dim iouter As Integer
Dim inner As Integer
For iouter = 1 To 5
For inner = 2 To 4
'do something
Next inner, iouter
End Sub
Exit For
The Exit For statement lets you exit the loop early.
Important
Remember that the loop counter is just a normal variable and its value "could be" changed from inside the loop.
Always ensure that the loop variable is not changed from inside the For - Next loop.
Be aware that when a For - Next loop finishes the index variable will actually have incremented past the final value.
© 2024 Better Solutions Limited. All Rights Reserved. © 2024 Better Solutions Limited TopPrevNext