
π This article includes 1 downloadable practice file β
π Excel VBA Course Β· Lesson 2 of 15 β see all lessons
In this article
Almost every macro reads or writes cells, and in VBA a cell or block of cells is a Range. Master a handful of Range techniques and most automation becomes straightforward.
Range vs Cells
Range("B2").Value = 100 ' address as text
Cells(2, 2).Value = 100 ' row 2, column 2 β same cell
Range("A1:C10").Interior.Color = vbYellow
Range(Cells(1, 1), Cells(10, 3)).ClearContents
Use Range("β¦") for fixed addresses and Cells(row, col) inside loops where the row or column is a variable.
Always say which sheet
With ThisWorkbook.Worksheets("Data")
.Range("A1").Value = "Report"
.Cells(2, 1).Value = Date
End With
An unqualified Range refers to whatever sheet is active at that moment. Qualifying with a sheet (and the leading dot inside With) removes a whole class of bugs.
Offset: move relative to a cell
Range("A1").Offset(1, 0).Value = "below A1" ' A2
Range("A1").Offset(0, 2).Value = "two right" ' C1
Resize: grow a range
Range("A2").Resize(5, 3).Select ' A2:C6
Offset + Resize together are perfect for βthe data below the headerβ: rng.Offset(1).Resize(rng.Rows.Count - 1).
CurrentRegion: the block around a cell
Dim data As Range
Set data = Range("A1").CurrentRegion ' like Ctrl+A inside a table
MsgBox data.Address & " has " & data.Rows.Count & " rows"
Rows, columns and counting
Rows(5).Delete
Columns("D").AutoFit
Range("A1:A100").Rows.Count ' 100
Application.WorksheetFunction.CountA(Range("A:A")) ' non-empty cells
Value, Text and Formula
| Property | Returns |
|---|---|
.Value |
The underlying value (a date is a date, 0.5 is 0.5) |
.Text |
What is displayed (β50%β, β##β) |
.Formula |
The formula as text, e.g. =SUM(A1:A5) |
Fast bulk read/write
Dim v As Variant
v = Range("A2:D5001").Value ' 5,000 rows into memory in one step
' ...work on v(r, c)...
Range("A2:D5001").Value = v ' write back in one step
Finding where data ends is covered in 5 ways to find the last row.
Try it yourself: step by step
- Open the practice workbook with the course macros imported.
- In the Immediate window (Ctrl+G) type
? Worksheets("Data").Range("A1").CurrentRegion.Addressβ$A$1:$H$61. - Type
Worksheets("Data").Range("A2").Resize(5, 8).Selectand press Enter β the first five data rows are selected. - Try
? Worksheets("Data").Range("A1").Offset(3, 2).Valueto read the region of the third invoice. - Write a macro that copies the whole CurrentRegion to a new sheet using one line:
rng.Copy Worksheets.Add.Range("A1").
π Practice files for this article
- πPractice workbook with all course macros (.xlsm)Open it, click Enable Content in the yellow bar, go to the Macros sheet and press any button. 60 sales rows included to test on.β¬ XLSM Β· 29 KB
Free to use for learning. Files with macros (.bas) are plain text β import them with Alt+F11 β File β Import File, and always test on a copy.