VBA For Each: loop through every cell in a range

For Each walks through the cells of a range one by one, with no counter to manage. It is the shortest way to process a whole column: raise prices, check stock levels, count matches.

In short: For Each cell In Range("B2:B" & lastRow) … Next cell runs the body of the loop once for each cell in the range. cell is the current cell, and cell.Value reads or writes its contents.

What you need to know: For Next, find the last row and If Then Else.

Try it right now

The supplier is putting prices up. Every cell in column B needs to be multiplied by 1.05, however many items the list has.

Task The supplier is raising all prices by 5%. The macro RaisePrices should multiply every price in column B by 1.05, using For Each over the range from B2 down to the last row. The last row is already worked out for you.

ABCD
1ItemPrice
2Coffee beans 1 kg18.90
3Espresso beans 1 kg21.50
4Green tea, 100 bags6.40
5Sugar 1 kg1.79
6Coffee filters, pack of 1002.49
7Hot chocolate powder 500 g4.99

How For Each works

Sub RaisePrices()
    Dim cell As Range, lastRow As Long
    lastRow = Cells(Rows.Count, 1).End(xlUp).Row
    For Each cell In Range("B2:B" & lastRow)
        cell.Value = cell.Value * 1.05
    Next cell
End Sub
PartMeaning
Dim cell As RangeThe variable for the current cell. It is an object of type Range, not a number.
Range("B2:B" & lastRow)The range. The address is built from text and a number, so with lastRow = 7 it is B2:B7.
For Each cell In …Sets cell to B2, then B3, then B4, and so on.
cell.ValueThe contents of the current cell. Assigning to it writes straight to the sheet.
Next cellMoves on to the next cell. After the last one, the loop ends.

A range with several columns is visited row by row: for A1:B2 that is A1, B1, A2, B2. With a single column it makes no difference.

Reaching the cells next door

For Each only hands you the cells in the range. If you need a value from another column in the same row, use the Row property:

PropertyResult for cell B5
cell.Row5
cell.Column2
cell.Address$B$5
Cells(cell.Row, 3)the neighbouring cell C5

cell.Offset(0, 1) is shorter; it is covered in Offset and Resize.

Task The macro CheckStock should use For Each to go through every cell from B2 down to the last row. If the stock is below the minimum in column C of the same row, it writes the text Reorder in column D. Otherwise D stays empty.

ABCD
1ItemIn stockMinimumNote
2Copy paper A4 (box)1210
3Black toner23
4Lever arch files4025
5Ballpoint pens85100
6Envelopes600500
7Sticky notes820

This exercise is part of Premium.

Premium unlocks every exercise in every lesson, unlimited practice with fresh tasks and the final test with certificate.

See Premium Already Premium? Log in

The first exercise in this lesson is free.

Count and report

Counting works like adding up: a variable starts at 0 and goes up by 1 on every pass that matches. The message belongs after Next, or it appears once per cell.

For Each cell In Range("B2:B" & lastRow)
    If cell.Value >= Range("E2").Value Then met = met + 1
Next cell
MsgBox "Target met: " & met

Check compares the message character by character. How MsgBox joins text and numbers is covered in MsgBox and InputBox.

Task The macro TargetCheck should count how many stores met the target in E2 (sales at least as high as the target) and report it with MsgBox, exactly like this: Target met: 4 of 6 stores. Go through the sales with For Each and count all stores along the way.

ABCDE
1StoreSales
2Manchester52,300Target40,000
3Leeds38,900
4Boston61,250
5Denver29,800
6Bristol44,100
7Austin40,000

This exercise is part of Premium.

Premium unlocks every exercise in every lesson, unlimited practice with fresh tasks and the final test with certificate.

See Premium Already Premium? Log in

The first exercise in this lesson is free.

For Each or For Next?

For EachFor Next
Counternone, the variable is the cell itselfa number you use as the row number
Best forprocessing one column or any rangeseveral columns in the same row, running backwards, every other row
Backwardsnot possiblewith Step -1

For Each is not just for cells. Later you will use it to go through every sheet in a workbook (For Each ws In Worksheets), in the lesson on worksheets.

Common mistakes

The variable inside the quotes

Range("B2:B & lastRow") is one single string, so VBA sees the word lastRow rather than the number. The exercise reports "Run-time error '1004': Method 'Range' of object '_Global' failed". Write Range("B2:B" & lastRow), with the closing quote before the &.

Declaring the loop variable as a number

The variable in a For Each loop over cells must be an object: Dim cell As Range (or Variant). With As Long, the real VBA editor gives you a compile error.

MsgBox inside the loop

If the message sits before Next, it pops up for every cell, and the first one shows a running count. Check then tells you your first message reads "Target met: 1 of 1 stores", which is not the final result.

Running the macro twice

A macro that changes values in place (cell.Value = cell.Value * 1.05) raises them again the second time. In the exercises every run starts with the original data; in real Excel it does not. Write the result to its own column, or work on a copy.

In real Excel

For Each cell In Selection is a real time-saver: the macro then works on exactly the cells you selected with the mouse beforehand. That way you can build small helpers such as "raise the selected cells by 5%" and put them on a button. It does not suit the exercises, because Check knows nothing about a selection, but it is very handy day to day.

FAQ

Does the variable have to be called cell?

No. c or rng are common too. A descriptive name keeps the code readable.

Can I leave a For Each loop early?

Yes, with Exit For, just as in For Next. That pays off when you only need the first match.

Are blank cells skipped?

No. For Each visits every cell in the range, including empty ones. An empty cell has the value Empty, which counts as 0 in calculations. To leave them out, check first with If cell.Value <> "" Then.

Which is faster, For Each or For Next?

With typical office lists you will not notice a difference. Real speed comes from reading a whole range into an array in one go, which is covered in level 5.

Every loop compared, with a table of which one fits when: VBA loops overview.

Learn this next: Do While and Do Until

Loops without a fixed end: they keep going while a condition holds. You learn when that is useful and how to avoid an endless loop.

Learn Do While

Write to us

Choose language

Select your preferred language