In this video I am going to explain VBA for Loops
For loops are one of the effective methods of controlling the flow through your code.
It basically repeats a number of statements for a specified number of times.
You must specify a counter.
For (start of counter) to (end of counter) Lines of code
Next
The counter must be numeric, using A to G will not work.
All though setting the initial counter to 1 and repeating until it reaches 5 is an ideal
situation for using the For Loop, many times you are trying to advance through a page either
by row or by column.
So let me demonstrate by row.
we are going to the developer tab and click on Visual Basic
now we are going to insert new module to start our mondule we will enter
Sub boldeach() and when you press enter you will get an end
sub now we are going to define out values so we
are going to have r for row and c for column We are going to define them both as long or
long integers Dim r As Long
Dim c As Long
When looking at our sheet we can see that we would like to start on the second row and
the six column so we define are starting point for both of
them r = 2
c = 6
we will start out for loop by defining the range of data from
For r = 2 To 11
enter a couple of spaces
the end of a for loop is next and we are going to put another for
loop so we will say next r
so inbetween the for and the next we will put our cursor there and press tab to make
it easier to read
Then we select the first cell so use the sheet1 naming and then we specify
the cell it goes by row and then column so we say whatever
the row is and the second column select
Sheet1.Cells(r, 2).Select now we have selected that cell so we can say
ActiveCell.Font.Bold = True so now it goes to the next r
Next r
End Sub so let us F8 through this
so
now that we have seen it work, let us F5 so it continues
Now you can see that it has bolded all of the names
So I am going to unbold these values and we are going to go back to our code and
enter a for loop for the columns
very similar to the row for loop
For c = 6 To 10
we are specifying the second row and whatever the column is
Sheet1.Cells(2, c).Select once aqain we will make the font bold
ActiveCell.Font.Bold = True
Next c
So let us run this
now you can see that all the values are bold.
so that is a simple explanation of a for loop
Pleasse sub subscribe