How to Create a For Next Loop in Excel VBA!

Often when writing VBA code, one may need to repeat the same action or series of actions more than a couple of times. One could, in this case, write each action over and over in one’s code or alternatively one could use a better option and that is using loops. Looping is a key structural element of most programming languages. So, it’s a good idea to familiarize oneself with looping in order to not only write more efficient code but also to understand code others have written.

Looping allows one to handle repetitive tasks in one’s code using a loop structure. The simplest type of loop structure is the For…Next Loop structure. This structure handles cases where one has to repeat a certain action, or set of statements for a finite number of times specified.

So let’s look at a few simple examples of how to use the For…Next Loop Structure.

Introduction

We have a blank workbook and we want to give the cells A1: A20, a light blue fill using VBA first with a manual repetitive approach and then with a For…Next Loop. Our source workbook is shown below.

1) The first thing we are going to do is repeat the action required, a number of times, for each cell in the range, using VBA, in other words, we are not going to use the For…Next Loop structure at first. Since we want to see how to complete the task using a repetitive block of code only.

2) So, go to Developer>Controls>Insert and under the ActiveX Controls section, choose Command Button.

3) Draw a command button on the worksheet.

4) Using the Properties Window, name the Command button, cmdwithoutLoop and the caption to Fill without using a loop.

5) Right-click the button and select View Code.

6) Enter the following code for the button click event, in order to fill the cells in range A1: A20 with a light blue fill, using a repetitive coding block.

Private Sub cmdwithoutLoop_Click()

Cells(1, “A”).Interior.Color = RGB(156, 207, 212)

Cells(2, “A”).Interior.Color = RGB(156, 207, 212)

Cells(3, “A”).Interior.Color = RGB(156, 207, 212)

Cells(4, “A”).Interior.Color = RGB(156, 207, 212)

Cells(5, “A”).Interior.Color = RGB(156, 207, 212)

Cells(6, “A”).Interior.Color = RGB(156, 207, 212)

Cells(7, “A”).Interior.Color = RGB(156, 207, 212)

Cells(8, “A”).Interior.Color = RGB(156, 207, 212)

Cells(9, “A”).Interior.Color = RGB(156, 207, 212)

Cells(10, “A”).Interior.Color = RGB(156, 207, 212)

Cells(11, “A”).Interior.Color = RGB(156, 207, 212)

Cells(12, “A”).Interior.Color = RGB(156, 207, 212)

Cells(13, “A”).Interior.Color = RGB(156, 207, 212)

Cells(14, “A”).Interior.Color = RGB(156, 207, 212)

Cells(15, “A”).Interior.Color = RGB(156, 207, 212)

Cells(16, “A”).Interior.Color = RGB(156, 207, 212)

Cells(17, “A”).Interior.Color = RGB(156, 207, 212)

Cells(18, “A”).Interior.Color = RGB(156, 207, 212)

Cells(19, “A”).Interior.Color = RGB(156, 207, 212)

Cells(20, “A”).Interior.Color = RGB(156, 207, 212)

End Sub

7) Return to the worksheet and making sure Design Mode is not activated, click on the button and the cells specified in the code will now be filled with a light blue colour as shown below.

Now nothing stops one from using these kinds of repetitive programming blocks, however accomplishing the task this way can be time-consuming and laborious. Let’s say one had to fill 1000 cells with the blue fill (A1: A1000), to manually specify each cell in the code would be impractical. The general rule of thumb is that if one needs to type more than three lines of the same repetitive code, then one should rather look at accomplishing the task using a loop. However, it is not mandatory and when first starting out, one may prefer to use repetitive coding blocks, but as one’s VBA reaches more advanced levels, looping becomes a necessity.

Using the For Next Loop

The For…Next Loop is very simple to use and understand. In order to use the For…Next Loop, one must know the number of iterations required. Also, the start value and ending value must be specified. In our designated example, given above, we need to repeat the code 20 times in order to fill the cells A1: A20 with the light blue fill. We are starting at cell A1 and ending at cell A20.

The basic structure of the For…Next Loop is the following:

  • Declare the type of counting variable. This variable is used to count the number of times the action needs to be repeated, it, therefore, is most often of integer type.

Dim variable as Integer

  • Open the loop structure and state the starting and ending values of the counting variable.

For variable = 1 to the number of finite times, the action needs to be repeated

  • Enter the command/action/statement that needs to be repeated.
  • Using the Next keyword and the variable, loop to the next iteration.

Next variable

So, let’s see how to do this using our example.

1) First, things first, select the range A1: A20 and go to Home>Font>Fill>No Fill in order to restore the cells back to their original condition.

2) Then create another button, by going to Developer>Controls>Insert and under the ActiveX Controls section, choose Command Button and draw another button on the worksheet.

3) Using the Properties Window, name the Command button, cmdusingLoop and the caption to Fill using a For Next loop.

4) Right-click the button and select View Code.

5) Enter the following code for the button click event in order to fill the cells in range A1: A20 with a light blue fill, using a For…Next Loop structure.

Private Sub cmdusingLoop_Click()

Dim varcounter As Integer

 

For varcounter = 1 To 20

Cells(varcounter, “A”).Interior.Color = RGB(156, 207, 212)

Next varcounter

 

End Sub

6) Return back to the worksheet and make sure Design Mode is not activated click on the second button.

7) The cells A1: A20 are now filled with the light blue fill.

In our code, we have first set a variable called varcounter of integer type. This is the variable that is going to keep track of the number of iterations, we will specify using the loop. We then open the For Next…Loop structure using the For keyword and our counting variable. We also designate the starting value for our variable and where we want it to end, in this case, our starting value is 1 and our ending value is 20. For our required action, instead of writing out each row individually as we did before in the repetitive coding block, we simply use the variable instead. We then use the Next keyword in order to iterate or repeat the action, according to the number of times specified.

We can see that using the For…Next loop structure considerably lessened the code needed, which is one distinct advantage of using loops. Our code also looks neater and is easier to understand. Also if let’s say we had to fill the cells A1: A1000 with the light blue fill, instead of manually specifying the cells to be filled as we did when we were using the repetitive coding block, we could just adjust the code and in the For line set the end value to 1000 instead of 20. When the button is clicked, the cells from A1: A1000 would now be filled. This would save a considerable amount of typing and effort. The adjusted code for the Loop is shown below, in the case of A1000 being the last cell needing to be filled with the light blue fill.

Private Sub cmdusingLoop_Click()

 

Dim varcounter As Integer

 

For varcounter = 1 To 1000

Cells(varcounter, “A”).Interior.Color = RGB(156, 207, 212)

Next varcounter

End Sub

Using the Step Keyword with the For Next Loop

The Step keyword is an optional keyword that can be used in conjunction with the For…Next Loop Structure. By default without it, the For…Next Loop size is 1. When the Step value is specified, the counting variable increments by the specific step size set. The Step value can be either a positive or a negative integer. By specifying the Step value, one directly increments the counter as the loop proceeds. This concept is best demonstrated with an example.

Using a Positive Step Value

We now would like to fill every second cell in the range A1: A20, starting on cell A1, and then moving to A3 and so on,  with a light green fill, using the For…Next Loop structure with the Step keyword, and a positive step value. In this case, our step value would be positive 2, since we are incrementing using a value of 2.

1) On the worksheet called Step, go to Developer>Controls>Insert and under the ActiveX Controls section, choose Command Button and draw a button on the worksheet.

2) Using the Properties Window, name the Command button, cmdusingloopwithStep and the caption to Fill using a For Next loop With a Positive Step Value.

3) Right-click the button and select View Code.

4) Enter the following code for the button click event in order to fill every second cell in range A1:A20 with a light green fill (we will start on cell A1 and fill this cell with the light green fill and then every second cell from there onwards will also receive the light green fill), using a For…Next Loop structure with the Step keyword.

Private Sub cmdusingloopwithStep_Click()

Dim icounter As Integer

For icounter = 1 To 20 Step 2

Cells(icounter, “A”).Interior.Color = RGB(171, 248, 128)

Next icounter

End Sub

5) Return back to the worksheet and make sure Design Mode is not activated click on the button.

6) Every second cell in the range is now filled with the light green fill, starting with cell A1 and then moving by an increment of 2, due to us specifying using the Step keyword.

Using a Negative Step Value

We now would like to fill cells A2, A4, A6, A8, A10, A12, A14, A16, A18 and A20 with a grey fill, using the For…Next Loop structure with the Step keyword, using a negative step value. In this case, our step value is negative 2 since we are starting at cell A20 and then counting down technically due to the negative 2 value.

1) On the worksheet called Step, go to Developer>Controls>Insert and under the ActiveX Controls section, choose Command Button and draw the second button on the worksheet.

2) Using the Properties Window, name the Command button, cmd using loop with negative Step and the caption to Fill using a For Next loop With a Negative Step Value.

3) Right-click the button and select View Code.

4) Enter the following code for the button click event in order to fill the cells A2, A4, A6, A8, A10, A12, A14, A16, A18 and A20 with a grey fill, using a For…Next Loop structure with the Step keyword and a negative value.

Private Sub cmdusingloopwithnegativeStep_Click()

 

Dim icountertwo As Integer

 

For icountertwo = 20 To 1 Step -2

Cells(icountertwo, “A”).Interior.Color = RGB(173, 173, 173)

Next icountertwo 

End Sub

5) Return back to the worksheet and make sure Design Mode is not activated click on the button.

6) Every second cell in the range is now filled, starting with cell A20 and then moving 2 up, with the grey fill, due to us specifying using the Step keyword.

7) Remember to save your workbook as a macro-enabled workbook if you haven’t done so already.

We can see when using the For…Next Loop structure with a negative Step value, the sequence is slightly different and we start counting from the highest value downwards.

Download Working File

LoopsForNext

Conclusion

Looping allows one to handle repetitive actions, in an efficient manner. VBA provides different types of Loops and the simplest one is the For…Next Loop, and this is used when one has a finite number of actions/iterations needing to be completed. This loop structure can also be used in conjunction with a step value which can be either positive or negative, which allows slightly more flexibility and functionality with respect to incrementing.

Please feel free to tell us if you use the For…Next Loop structure in your VBA code.

Review Section: Test your Understanding

1) What is a loop?

2) When does one use a looping structure and what are the key advantages of using loops in one’s VBA code?

3) What is the general syntax of the For…Next Loop?

4) What is the difference between using a positive Step Value versus a negative Step Value in a For…Next Loop.

5) Using a For…Next Loop structure, create a macro that fills the columns A: J with a light grey fill.

6) Using a For…Next Loop structure, create a macro that fills every second column from Column A (starting at Column A) to Column J with a light blue fill.

Useful Links

Looping in Excel

Using the For Next Loop in Excel

A complete introduction to VBA Loops

Taryn is a Microsoft Certified Professional, who has used Office Applications such as Excel and Access extensively, in her interdisciplinary academic career and work experience. She has a background in biochemistry, Geographical Information Systems (GIS) and biofuels. She enjoys showcasing the functionality of Excel in various disciplines.

In her spare time when she’s not exploring Excel or Access, she is into graphic design, amateur photography and caring for her two pets, Pretzel and Snoopy.

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *

Solve the Math * Time limit is exhausted. Please reload CAPTCHA.