For - Next

This should be applied when you predict in advanced how many times you want to loop.


Dim icount As Integer 
For icount = 1 To 10

Next icount

The Step 1 is optional

Dim icount As Integer 
For icount = 1 To 10 Step 1

Next icount

You are free to leave off the name of the variable from the Next statement, but is should be included for completeness.

Dim iyear As Integer 
For iyear = 2006 To 2000 Step -1

   iyear = iyear - 1
Next

choose
Examples with Step 0.3 and Step 2.2


Nested For Loops

When used within nested For loops, Exit For transfers control to the loop that is nested one level above the loop where Exit For occurs.
For iouter = 1 To 5

   For inner = 2 To 4 
''do something
   Next inner
Next iouter

Combine Next Statements

You can also combine Next statements onto one line

For iouter = 1 To 5 
   For inner = 2 To 4
''do something
Next iinner, iouter

It is better to use individual lines for your Next statements and also makes code easier to read.


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 Loop finishes the index variable will actually have incremented past the final value.


© 2019 Better Solutions Limited. All Rights Reserved. © 2019 Better Solutions Limited TopPrevNext