Skip to content

Point at cells with Range, Cells, Offset and CurrentRegion

Write VBA9 minPremium

Builds on Read VBA as objects, properties and methods.

An HR coordinator in Halifax gets the staff list as a new export every month, and it's never the same length. Her macro has to find the whole list wherever it ends, write next to it, and leave alone the notes someone keeps under it.

How it works

RowAB
1You writeIt means
2Range("B2"), Range("B2:D9")A cell or block by its address, as in a formula
3Cells(4, 2)Row 4, column 2: B4. Numbers suit code where the row changes
4Range("A2").Offset(1, 2)1 row down and 2 columns right of A2: C3. Negative numbers go up or left
5Range("A1").CurrentRegionThe block around A1, out to the first empty row and column

Cells and Offset both take the row first and the column second. Cells(4, 2) is B4, and Cells(2, 4) is D2.

CurrentRegion is the block Excel selects when you press CtrlA (CmdA on a Mac) inside a list: it grows with the data and stops at an empty row or column. .Rows.Count counts its rows, headings included.

CurrentRegion stops at the first empty row and column, so the list comes with it and the note under the gap doesn't. Cells(4, 2) is row 4, column 2.

Example

VBA
Sub CountStaff()
Range("F1").Value = "Staff"
Range("F2").Value = Range("A1").CurrentRegion.Rows.Count - 1
End Sub
Writes how many people are on the list in F2, under a heading in F1, however long the list is.

With five people under the headings, CurrentRegion.Rows.Count is 6, and the macro writes 5.

Common mistakes

  • Swapping the row and the column. Cells(2, 5) is E2, row 2 and column 5; for B5, write Cells(5, 2).
  • A fixed range such as Range("A1:C200") for a list that changes length. It takes in empty rows, or misses new ones; use CurrentRegion.
  • A blank row inside the list. CurrentRegion stops at it, so the rows after it are left out. Remove the blank row, or find the last row as the next lessons show.

In short

  • Range takes an address, Cells(row, column) takes numbers, and Offset(rows, columns) moves from a cell.
  • Rows come first in both Cells and Offset.
  • Range("A1").CurrentRegion is the whole block of data around A1, and .Rows.Count counts its rows.

Practice

Premium

4 exercises: 3 macros and 1 quiz question.

Practice is part of Premium

Every lesson is free to read, and you can practice the free lessons without an account. This lesson's exercises are part of Premium, which you add to a free account.