Why every VBA macro starts with a Range
Open any macro that someone else wrote and count the lines that mention Range or Cells. In typical Excel code they make up a large share of all lines. Whatever a macro does, whether it formats a report, cleans an export, copies totals into a summary or checks a list for gaps, it has to say which cells it means before it can do anything to them. That is the job of the Range object, and it is the single most important thing to understand in Excel VBA.
This free first lesson of the Ranges & Cells course is for anyone who has opened the Visual Basic Editor, perhaps recorded a macro or pasted one from the web, and then felt unsure what all those Range("โฆ") lines actually point at. If you can type an address such as A2:D16 into the Name Box, you already know most of what you need. The macro in the lesson above, RangeTour, writes 15 fictional orders into a new sheet, formats them, highlights the four orders over 1,500 and reports on its own ranges. This article takes the same example apart: what a range is, how VBA builds one, how to check that you built the right one, and which mistakes cost people the most time.
The concept: an address in, an object out
In the worksheet, an address such as D2:D16 is just text. In VBA, ws.Range("D2:D16") turns that text into an object: a live handle on those fifteen cells that you can read from, write to, format, clear, count or ask questions. The same object can be one cell, a rectangular block, a whole column, a whole row, a named cell, or even several separate blocks. Because the address is ordinary text, you can also build it while the macro runs, for example from a row number stored in a variable.
An object has properties, things it is or has, and methods, things it can do. .Value, .Formula, .NumberFormat, .Address and .Interior.Color are properties: you read them, and most of them you can also set. .ClearContents, .Copy and .AutoFit are methods: you call them, and the range does something. Nearly every line that touches the sheet in RangeTour has the shape range, dot, property, equals, value or range, dot, method.
Finally, a range always lives on a particular worksheet, and that worksheet lives in a particular workbook. The full path is Application.Workbooks("Orders.xlsm").Worksheets("Data").Range("D2"). You rarely type all of it, but you should always know which sheet a range belongs to. The lesson macro makes that explicit by keeping its new sheet in a variable called ws and writing ws.Range(โฆ) every time, so the code never depends on which sheet happens to be active.
The forms of Range you will meet
These are the address forms the lesson uses, plus two you will see in other people's code. All of them return a Range object:
ws.Range("A1") ' one cell
ws.Range("A1:D16") ' a block, written as you would in the Name Box
ws.Range("A2", "D16") ' the same kind of block, given as two corners
ws.Range("D:D") ' the whole of column D
ws.Range("1:1") ' the whole of row 1
ws.Range("D2:D" & lastRow) ' an address built from a variable
ws.Range("TaxRate") ' a defined name, created in Excel first
ws.Cells(2, 4) ' row 2, column 4: the same cell as D2
The last line is a preview of the next lesson. Cells(row, column) uses numbers instead of letters, which is exactly what a loop wants. Both forms return the same kind of object, so everything you learn here about .Value, .Address and formatting applies to Cells as well.
The worked example: 15 orders and a small report
Here is the data the macro writes, row by row. Column D is formatted with #,##0.00, so 420 appears as 420.00 while the stored value is still the number 420. The last column shows which cells the For Each loop colours pale yellow because their value is greater than the constant LIMIT of 1,500.
| Row | A: Order | B: Region | C: Customer | D: Amount | Fill |
|---|---|---|---|---|---|
| 2 | 1001 | North | Alder Cafe | 420.00 | |
| 3 | 1002 | South | Birch Studio | 1,250.00 | |
| 4 | 1003 | East | Cedar Dental | 380.00 | |
| 5 | 1004 | West | Elm Bakery | 960.00 | |
| 6 | 1005 | North | Fern Florist | 2,140.00 | yellow |
| 7 | 1006 | East | Granite Gym | 515.00 | |
| 8 | 1007 | South | Harbor Books | 780.00 | |
| 9 | 1008 | West | Iris Optics | 1,630.00 | yellow |
| 10 | 1009 | North | Juniper Design | 290.00 | |
| 11 | 1010 | East | Kestrel Bikes | 1,105.00 | |
| 12 | 1011 | South | Linden Hotel | 870.00 | |
| 13 | 1012 | West | Maple Garage | 1,990.00 | yellow |
| 14 | 1013 | North | Nettle Tea Room | 640.00 | |
| 15 | 1014 | East | Oakwood Joinery | 1,340.00 | |
| 16 | 1015 | South | Pine Clinic | 1,725.00 | yellow |
Next to the data, in F1:G6, the macro writes a little report in which the ranges describe themselves. You can reproduce every one of those numbers with an ordinary worksheet formula. That is a habit worth keeping: whenever a macro reports a number, check it once with a formula that does not depend on your code.
| Report line | VBA that fills it | Worksheet formula check | Result |
|---|---|---|---|
| Rows | data.Rows.Count | =ROWS(A2:D16) | 15 |
| Address | data.Address | =CELL("address",A2)&":"&CELL("address",D16) | $A$2:$D$16 |
| Cells | data.Cells.Count | =ROWS(A2:D16)*COLUMNS(A2:D16) | 60 |
| Total | "=SUM(" & amounts.Address & ")" | =SUM(D2:D16) | 16,035.00 |
| Orders over 1,500 | the counter bigOrders | =COUNTIF(D2:D16,">1500") | 4 |
| Average order | not in the report | =AVERAGE(D2:D16) | 1,069.00 |
| North total | not in the report | =SUMIF(B2:B16,"North",D2:D16) | 3,490.00 |
The chart below shows the fifteen amounts that live in D2:D16. Only four bars clear the dashed line, which is why the report says 4 and why exactly four cells turn yellow. If you change LIMIT to 1,000 in the code, three more bars (1,250, 1,105 and 1,340) cross the line and the count becomes 7.
Line by line: the range ideas inside RangeTour
Six short patterns do all the work in the macro. Here they are on their own, taken from the lesson code (only the loop is shortened to a one-line If):
' 1. one statement fills four cells
ws.Range("A1:D1").Value = Array("Order", "Region", "Customer", "Amount")
' 2. an address is text, so it can be built
ws.Range("A" & i + 2).Value = 1001 + i
' 3. keep blocks in variables: objects need Set
Set data = ws.Range("A2", "D" & lastRow)
Set amounts = ws.Range("D2:D" & lastRow)
' 4. format a whole block in one line
amounts.NumberFormat = "#,##0.00"
' 5. visit every cell of a block
For Each cell In amounts.Cells
If cell.Value > LIMIT Then cell.Interior.Color = RGB(254, 243, 199)
Next cell
' 6. let a range describe itself
Debug.Print data.Address(False, False) & " holds " & data.Cells.Count & " cells"
- Writing a block at once. A one-dimensional
Array(โฆ)with four items fits exactly into the four cells of a one-row range. If the range were wider than the array, the extra cells would show#N/A. - Building addresses.
"A" & i + 2works because VBA does the arithmetic first and then glues the result to the letter: wheniis 3, the address isA5. - Range variables.
Dim data As Rangedeclares the variable, andSetfills it. After that,datais a short, readable name forA2:D16on that exact sheet. - Formatting a block. Setting a property on a multi-cell range applies it to every cell. There is no need to loop for a format that is the same everywhere.
- Looping cell by cell. When each cell needs its own decision,
For Each cell In amounts.Cellshands you one single-cell range at a time. In the lesson code theIfis a block that also adds one tobigOrders; the one-line form above is shortened for reading. - Self-description.
.Address,.Rows.Countand.Cells.Countare your sanity check. Print them while developing and you will catch an off-by-one row before it reaches a report.
Step by step: run and inspect it in Excel
Follow these steps to run the lesson macro and then look at its ranges from the inside. They work in desktop Excel for Windows and Mac; Mac menu names are given where they differ.
- Open a new workbook so nothing valuable can be overwritten.
- Press
Alt+F11to open the Visual Basic Editor (on a Mac: Tools โ Macro โ Visual Basic Editor). - Choose Insert โ Module and paste the
RangeTourmacro from the lesson into the empty code window. - Open the Immediate window with
Ctrl+G(Mac: View โ Immediate Window). This is whereDebug.Printwrites. - Click inside
Sub RangeTourand pressF5. The Immediate window showsA2:D16 holds 60 cells, and a message box reports the address and the total. - Back in Excel, click into the Name Box (left of the formula bar), type
A2:D16and press Enter. Excel selects exactly the block thatdatarefers to. - Return to the editor, type
?ActiveSheet.Range("D2:D16").Addressinto the Immediate window and press Enter:$D$2:$D$16. Then try?ActiveSheet.Range("D2:D16").Cells.Count: 15. - To watch the loop work, click on the line
For Each cell In amounts.Cells, pressF9to set a breakpoint, run the macro again and step withF8. Hover overcell.Valueto see each amount in turn. - Save as Excel Macro-Enabled Workbook (*.xlsm) if you want to keep the code.
? in the Immediate window is short for Debug.Print. Any expression that returns a value works there, so it is the fastest way to ask a range a question: ?Range("A1:D16").Columns.Count answers 4 without running a whole macro.Reading and writing: Value, Formula and NumberFormat
Three properties cover most everyday work, and mixing them up causes most beginner surprises. .Value is the stored content: a number, text, a date or empty. .Formula is what you would see in the formula bar, so writing ws.Range("G5").Formula = "=SUM(D2:D16)" creates a live formula that updates when the data changes, while writing .Value = 16035 stores a fixed number that does not. .NumberFormat changes only how a number looks. The lesson macro uses all three: values for the orders, a formula for the total, and a number format for the amounts.
Reading works the same way. x = ws.Range("D6").Value puts 2140 into x. Reading .Value from a multi-cell block returns a two-dimensional array instead of a single value, which is how fast macros read thousands of cells in one go; a later course on arrays builds on that. For now, the rule is simple: one cell gives one value, a block gives a grid of values.

Common mistakes and how to spot them
These are the range mistakes that show up again and again in real macros. Each one comes with the symptom that gives it away.
- Forgetting Set.
data = ws.Range("A2:D16")withoutSetstops with Object variable or With block variable not set (error 91). Symptom: the error points at a line that assigns a range. - Forgetting the ampersand.
"D2:D" lastRowis a syntax error and the line turns red as soon as you leave it. It must be"D2:D" & lastRow. - An unqualified Range.
Range("A1")withoutws.means the active sheet. The macro works while you test it and then writes into the wrong sheet the day someone runs it from another tab. Symptom: data appears on a sheet you did not expect. - Hard-coding the last row.
Range("D2:D16")is fine for a fixed example, but real exports grow. Symptom: totals that ignore the newest rows. Build the address from a variable, and learn to find the last row in lesson 7 of this course. - Addresses that do not move. If someone inserts a row above B4,
Range("B4")in your code still points at B4, now the wrong cell. A defined name such asRange("TaxRate")follows the cell. Symptom: a macro that suddenly reads a header or a blank. - Commas in an address.
Range("A2:A5,C2:C7")is a multi-area range. Formatting reaches all ten cells, but.Rows.Countsilently returns 4, the size of the first area only. Symptom: a loop that stops halfway. Use.Areaswhen each block needs real work. - Value versus Text.
.Valuereturns the stored number,.Textreturns what the cell displays, including #### when the column is too narrow. Symptom: comparisons that fail only on some screens. Prefer.Valuefor logic.
Quick reference: range members and shortcuts
The members and keys used in this lesson, in one place:
| Item | Kind | What it does |
|---|---|---|
Range("A2:D16") | Object | A block of cells by address |
Range("A2", "D16") | Object | The same block given by two corner cells |
Cells(r, c) | Object | One cell by row and column number |
.Value / .Formula | Property | Stored content / formula text |
.NumberFormat | Property | How a number is displayed, e.g. "#,##0.00" |
.Interior.Color, .Font.Bold | Property | Fill colour, bold text |
.Address, .Address(False, False) | Property | $A$2:$D$16 or A2:D16 |
.Rows.Count, .Cells.Count | Property | Size of the block |
.ClearContents / .Clear | Method | Remove values only / values and formats |
.Areas | Property | The separate blocks of a multi-area range |
ROWS, COLUMNS, SUM, COUNTIF, SUMIF | Worksheet functions | Check the macro's report independently |
Alt+F11, F5, F8, F9, Ctrl+G | Shortcuts | Editor, run, step, breakpoint, Immediate window |
Real-world uses
Once you can point at any block of cells with confidence, a whole class of chores becomes a few lines of code:
- Formatting a fresh export. A finance assistant receives the same ledger export every week. A macro sets number formats on the amount column, bold headers, borders on the data block and fitted column widths, all through a handful of range variables.
- Flagging exceptions. A purchasing team wants every order above an approval limit highlighted before the weekly review. A
For Eachloop over the amount column does it, and a counter tells the reviewer how many there are, just likebigOrdersin the lesson. - Writing summary formulas. Instead of typing totals by hand under a list that changes length, a macro builds
"=SUM(" & amounts.Address & ")"from the real range, so the formula always covers exactly the data. - Clearing an input area. A template has an input block that must be emptied every month without losing its formatting.
ws.Range("InputArea").ClearContentson a defined name does it safely. - Region summaries. A sales lead needs totals per region in a fixed layout. The macro writes
SUMIFformulas whose ranges come from range variables, which gives the figures shown in the chart below.
=SUMIF(B2:B16,"South",D2:D16) and its siblings return it. South (4,625) and West (4,580) lead, although West has only three orders.
What you will build in the rest of this course
This first lesson is free. The other seven lessons belong to the full Ranges & Cells course, a one-time purchase of $9.90, and each one takes the same order data a step further:
Cells(row, column). Address cells by numbers instead of letters, the form every loop wants. You will convert between letters and numbers, combine Cells with Range to describe blocks, and rewrite the order loop so it no longer glues text addresses together.
Selecting vs Referencing. Recorded macros are full of .Select and Selection. This lesson shows why the RangeTour macro never needed either, how to turn recorded code into fast, direct references, and why that also stops macros from failing when the screen changes.
Reading and Writing Values. A deeper look at .Value, .Value2, .Text and .Formula: dates, blanks, errors, and reading or writing a whole block as an array in a single statement.
Moving Around with Offset and Resize. Point at the cell next to the one you found, or grow a single cell into a block of any size. These two methods let one reference walk across a report without any address arithmetic.
CurrentRegion and UsedRange. Let Excel tell you where the data is. You will compare the two, see where each one is fooled by stray formatting or blank rows, and pick the right one for exports of unknown size.
Finding the Last Row. The technique behind nearly every robust macro: find the true last row of a column with End(xlUp) and friends, so code like the lesson's D2:D16 becomes D2:D plus however many rows arrived today.
Being Explicit About the Sheet. Qualify every range with its sheet and workbook, use With blocks and sheet variables, and make macros that behave the same no matter which tab or file is active when they run.
Summary
The Range object turns an address into something your code can work with. You can write a single cell or a whole block, build addresses from variables, keep blocks in variables with Set, format a block in one line, visit its cells one by one with For Each, and ask it for its .Address and size to check that it is the block you meant. Qualify ranges with their sheet, avoid commas unless you only format, and confirm every reported number once with a worksheet formula.
Scroll back up, run RangeTour, and then make one change: set LIMIT to 1,000 and run it again. Seven yellow cells, a report that says 7, and you will have controlled fifteen cells with one constant and one range variable.
Frequently asked questions
What is the Range object in Excel VBA?
Range is the VBA object that represents one cell or a group of cells on a worksheet. You create it from an address such as Range("A2:D16") and then read, write, format or inspect those cells through its properties and methods.
What is the difference between Range and Cells in VBA?
Range takes an address as text, such as "D2", while Cells takes a row and column number, such as Cells(2, 4). Both return the same kind of Range object, and Cells is usually easier inside loops.
Why do I need Set when assigning a range to a variable?
A range is an object, and VBA assigns objects with the Set keyword. Without Set the line fails with error 91, object variable or With block variable not set.
How do I use a variable in a Range address?
Build the address as text with the ampersand, for example Range("D2:D" & lastRow). VBA evaluates the variable first and then joins it to the letters.
How do I select a range without using Select in VBA?
You usually do not need to select at all: refer to the range directly, for example ws.Range("D2:D16").NumberFormat = "#,##0.00". Direct references are faster and do not depend on which sheet is active.
What is the difference between ClearContents and Clear?
ClearContents removes the values and formulas but keeps the formatting, while Clear removes values and formatting together.
Keep going: Ranges & Cells
This free lab is lesson 1 of 8. Unlock the other 7 hands-on labs, the final exam and your certificate for a one-time CHF 9.90.
- Cells(row, column)
- Selecting vs Referencing
- Reading and Writing Values
- Moving Around with Offset and Resize
- CurrentRegion and UsedRange
- Finding the Last Row
- Being Explicit About the Sheet