For Each Next
- 02:03
How the For Each Next loop can be used to perform a set of instruction multiple times.
Downloads
No associated resources to download.
Transcript
Now that we can declare variables, let's use them in some code.
There are lots of ways to write VBA code to enable a set of instructions to be performed multiple times.
These are collectively known as looping procedures.
We'll explore a number of different looping procedures in general, all perform a similar task, but some procedures are better suited to certain situations than others.
The first looping procedure that we'll look at is the four each next loop. The code in the example converts the contents of all the cells in a selection to upper case.
The first line of code declares a variable.
Then the variable is given the name cell and it can hold range objects.
The loop starts with the syntax for each.
Here we are telling the code to evaluate each cell range Object in a selection.
Selection is the VBA code for the range of cells selected in the worksheet.
The next line of code provides the instruction for the action to perform on each cell.
Here the cell's value is converted into uppercase using the U case VBA function.
The four each next loop is closed with next and we are instructing the code to loop back to the start to evaluate the next cell object in the selection.
Once all of the cells have been evaluated and there are no further cells to loop onto the procedure ends.