For Each Next Workout
- 05:31
Workout to demonstrate the For Each Next loop in Excel VBA.
Transcript
In this workout, we are required to use four each looping procedure to write VBA code to make each cell value in range one bold.
Here we'll note that range one spans all the way from cell CB 8 right the way across to cell E8.
Let's jump in and write our VBA code.
We go developer Visual Basic and we will write our VBA code in a module insert module.
Let's call our workout, workout 2, sub workout 2.
Now, before we write our code, it's a good idea to plan out our code before we begin writing in the Visual Basic Editor in order to build for each next looping procedure.
To make the cell contents bold in the range, two range variables are required and must be declared one for each cell, we'll call it CL in the range, and the second for the range itself.
Here the XL range named range one, let's declare our variables.
We declare CL as a range variable.
CL will take each of our cells in the specified range and we declare quarters one as another range variable as quarters.
One is a range. Variable set is required to assign the range, range 1 to the range variable quarters one quarters one is set to be equal to range one in the front end of Excel.
Let's write the four each looping procedure to move through each cell CL in the range.
And we start with the syntax for each.
Here we want to loop through each cell or CL in the range quarters one, and we say for each CL In quarters one, you'll note that excel VBA capitalizes those required syntax words of four each.
and in. Next we want to assign each of those cells CL We want to assign their font property to be bold.
So we say CL font bold equals true.
The bold property of the font object of the CL range object is assigned to be equal to true.
It's good practice to indent using tab the lines of instructional code within a loop.
Finally, we close the loop by writing.
Next CL, we go onto the next cell range object within the wider range quarters, one back in the front end of Excel.
We can execute our code or we can choose to step through our code to see how the procedure works.
Let's step through our code, select the top line of our code in Excel VBA and we can press the shortcut key F8 to step into the code to watch it execute line by line, we step into the code and the first cell within that range is assigned it's font property to be bold and we can see that.
Next CL, we move across to the next cell in the range of quarters.
One, the font property is assigned to be bold.
We go to the next CL.
That font property is assigned to be bold.
We go to the final cell and that font is assigned to be bold.
There are no more next CLs and our sub procedure ends.