VBA Macro to Loop through Rows in Excel

Updated on August 22, 2012

What is a Loop?

A loop in VBA is instructions to perform a particular task until a given conditional statement is true. There are other methods of repetitively performing tasks within VBA and loops would probably my last choice. That said they are still useful and very easy for the beginner.

Setting up a loop is fairly simple. Here's a few things you need to know first:

• When creating loops I like to use the Cells method. This method is very similar to the Range method. However, with the cells method you define the row and column using their corresponding numbers rather than their address. VBA will accept a variable for either coordinate.
• You will find that you will normally be performing loops on blocks of data. Within VBA you can use the len function to return the length of a cell. You can use the len function to instruct excel to execute until it encounters a cell with length of zero.
• There are several way to structure loops: For Each, Do While, For Next, Do Until. This module focuses on the Do Until method. This is probably the easiest for beginner. I will cover the others in future modules.
• When using text in VBA it must be enclosed in quotes.
• When conjoining text and variables use the "&" operator.

Why are loops so useful

For simplicity sake, I will make this task very basic. In fact it can easily be performed using Excels built in functions. However, once you understand the construction of a loop you can use it to perform as complicated of a task as you want.

The purpose of this macro is to input the formula

=A1*B1 in Cells C1

=A2*B2 in Cells C2

onward until length of the contents of a cell in column A equals zero.

Macro without a loop

Sub TestMacro()

Cells(1, 3).Formula = "=A1*B1"

Cells(2, 3).Formula = "=A2*B2"

Cells(3, 3).Formula = "=A3*B3"

Cells(4, 3).Formula = "=A4*B4"

Cells(5, 3).Formula = "=A5*B5"

Cells(6, 3).Formula = "=A6*B6"

Cells(7, 3).Formula = "=A7*B7"

Cells(8, 3).Formula = "=A8*B8"

Cells(9, 3).Formula = "=A9*B9"

Cells(10, 3).Formula = "=A10*B10"

End Sub

• Long and repetitive
• A new line of code must be added each time a new line of data is added
• Hard to identify errors

Using a Do Until Loop

Sub TestLoop()

Dim row As Integer

row = 1

Do

Cells(row, 3).Formula = "=A" & row & "*B" & row

row = row + 1

Loop Until Len(Cells(row, 1)) = 0

End Sub

• I have not covered this in a subsequent hub yet. However, you will notice in the example that text is enclosed in quotes when conjoining text and variables you must use the & operator.
• If you look at code from other sources you may notice the conditional statement is after the Do statement instead of after the Loop statement. Either way it works the same.

Congratulations! You have quite a lot in a short time. We are now ready to tackle our first project. Click here when you are up for the challenge.

5

2

40

10

6

3

2