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
| Row | A | B |
|---|---|---|
| 1 | You write | It means |
| 2 | Range(, Range( | A cell or block by its address, as in a formula |
| 3 | Cells( | Row 4, column 2: B4. Numbers suit code where the row changes |
| 4 | Range( | 1 row down and 2 columns right of A2: C3. Negative numbers go up or left |
| 5 | Range( | The block around A1, out to the first empty row and column |
Cells and Offset both take the row first and the column second. Cells( is B4, and Cells( 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.
Cells( 4, 2) is row 4, column 2.Example
Sub CountStaff() Range("F1"). Value = "Staff" Range("F2"). Value = Range( "A1"). CurrentRegion. Rows. Count - 1 End Sub
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(is E2, row 2 and column 5; for B5, write2, 5) Cells(.5, 2) - A fixed range such as
Range(for a list that changes length. It takes in empty rows, or misses new ones; use"A1:C200") CurrentRegion. - A blank row inside the list.
CurrentRegionstops 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
Rangetakes an address,Cells(takes numbers, androw, column) Offset(moves from a cell.rows, columns) - Rows come first in both
CellsandOffset. Range(is the whole block of data around A1, and"A1").CurrentRegion .Rows.Countcounts its rows.
Practice
Premium4 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.
Have one? Sign in