For Next
- 02:31
How the For Each Next loop can be used to perform a set of instruction multiple times.
Downloads
No associated resources to download.
Transcript
The for next loop does the same job as a for each loop.
However, in a for next loop, a counter variable must be specified so that the procedure can iterate.
In this example, the procedure loops through all the cells in a range and applies a colour to each cell.
Let's walk through the code.
A range variable is declared and set Test area is a range variable and is set to be equal to the range in the spreadsheet named area.
A counter variable is also declared.
Note, a counter variable is declared as an integer as it'll be used to repeat the instructions.
The four next loop starts with a syntax four and then the counter variable.
Here we've named our counter variable I.
The next part of the code 1, 2, 5.
Here it's important we use the correct syntax for the counter using the word two.
The instruction specifies a cell in the test area object.
The cell's property directs the code to row I column one.
In this range where I equals one.
The code identifies row one column one of the test area range ie, here, cell C 55.
That includes the word project A.
The cell interior property is then assigned a colour using the VBA code equals RGB.
The RGB function can be used to assign a colour.
The next I instruction is required at the end of the four next loop.
And here next I will equal two and we go around the loop.
Again, this code loops through I equals two, then three, four, and finally five.
When I equals five, there is no next I, as we specified, I equals one to five and the procedure will end.