For - Next
This should be used when you know in advance how many times you want to loop.
Public Sub ForNext1()
Dim icount As Integer
For icount = 1 To 5
'do something
Next icount
End Sub
The Step 1 is optional because the default is plus 1.
Public Sub ForNext2()
Dim icount As Integer
For icount = 1 To 5 Step 1
'do something
Next icount
End Sub
Appending the variable name after the Next statement is optional, but is should be included for completeness.
Public Sub ForNext3()
Dim icount As Integer
For icount = 5 To 1 Step -1
'do something
Next
End Sub
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
For inner = 2 To 4
'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 can 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.
© 2022 Better Solutions Limited. All Rights Reserved. © 2022 Better Solutions Limited TopPrevNext