Tabellab

The Range Object: Point VBA at Any Cell

Lesson 1 of 8Reading

One macro, one finished report

In about a minute from now, a single macro will create a new sheet, write 15 orders into it, colour the header, highlight the 4 orders over 1,500 and pop up a message: 15 orders written to $A$2:$D$16, Total: 16,035.00. Every one of those steps runs through one object: Range. All companies, names and numbers are fictional.

Run it in four steps

  1. Open any workbook and press Alt+F11 to open the VBA editor (on a Mac: Tools โ†’ Macro โ†’ Visual Basic Editor).
  2. Choose Insert โ†’ Module.
  3. Paste the macro below into the empty window.
  4. Click anywhere inside Sub RangeTour and press F5 (or click the green Run button). Switch back to Excel: the new tab is already there.
The macro only adds a new sheet and writes into it. Nothing on your existing sheets is read or changed, and each run makes a fresh tab, so you can run it as often as you like.
Option Explicit

Sub RangeTour()
    Const LIMIT As Double = 1500

    Dim ws As Worksheet
    Dim data As Range
    Dim amounts As Range
    Dim cell As Range
    Dim regions As Variant
    Dim customers As Variant
    Dim orderValues As Variant
    Dim i As Long
    Dim lastRow As Long
    Dim bigOrders As Long

    ' --- 15 fictional orders, so the macro needs no file of yours ---
    regions = Array("North", "South", "East", "West", "North", _
                    "East", "South", "West", "North", "East", _
                    "South", "West", "North", "East", "South")
    customers = Array("Alder Cafe", "Birch Studio", "Cedar Dental", _
                      "Elm Bakery", "Fern Florist", "Granite Gym", _
                      "Harbor Books", "Iris Optics", "Juniper Design", _
                      "Kestrel Bikes", "Linden Hotel", "Maple Garage", _
                      "Nettle Tea Room", "Oakwood Joinery", "Pine Clinic")
    orderValues = Array(420, 1250, 380, 960, 2140, 515, 780, 1630, _
                        290, 1105, 870, 1990, 640, 1340, 1725)

    Set ws = ThisWorkbook.Worksheets.Add
    ws.Name = "Range tour " & Format(Now, "hh-mm-ss")

    ' 1. one statement fills four cells
    ws.Range("A1:D1").Value = Array("Order", "Region", "Customer", "Amount")

    ' 2. an address is text, so you can build it
    For i = 0 To UBound(orderValues)
        ws.Range("A" & i + 2).Value = 1001 + i
        ws.Range("B" & i + 2).Value = regions(i)
        ws.Range("C" & i + 2).Value = customers(i)
        ws.Range("D" & i + 2).Value = orderValues(i)
    Next i
    lastRow = UBound(orderValues) + 2          ' 16

    ' 3. keep whole blocks in variables (objects need Set)
    Set data = ws.Range("A2", "D" & lastRow)   ' A2:D16
    Set amounts = ws.Range("D2:D" & lastRow)   ' D2:D16

    ' 4. format a block in one line each
    With ws.Range("A1:D1")
        .Font.Bold = True
        .Font.Color = vbWhite
        .Interior.Color = RGB(30, 64, 175)
    End With
    data.Borders.Color = RGB(203, 213, 225)
    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)
            bigOrders = bigOrders + 1
        End If
    Next cell

    ' 6. a range describes itself
    ws.Range("F1").Value = "Report"
    ws.Range("F1").Font.Bold = True
    ws.Range("F2").Value = "Rows"
    ws.Range("G2").Value = data.Rows.Count
    ws.Range("F3").Value = "Address"
    ws.Range("G3").Value = data.Address
    ws.Range("F4").Value = "Cells"
    ws.Range("G4").Value = data.Cells.Count
    ws.Range("F5").Value = "Total"
    ws.Range("G5").Formula = "=SUM(" & amounts.Address & ")"
    ws.Range("G5").NumberFormat = "#,##0.00"
    ws.Range("F6").Value = "Orders over " & Format(LIMIT, "#,##0")
    ws.Range("G6").Value = bigOrders
    ws.Columns("A:G").AutoFit

    Debug.Print data.Address(False, False) & " holds " & data.Cells.Count & " cells"

    MsgBox UBound(orderValues) + 1 & " orders written to " & data.Address & vbNewLine & _
           "Total: " & Format(Application.WorksheetFunction.Sum(amounts), "#,##0.00") & vbNewLine & _
           bigOrders & " orders over " & Format(LIMIT, "#,##0") & " highlighted", _
           vbInformation, "Range tour"
End Sub

What you see on the new sheet

  • A1:D1: a blue header row with white bold text.
  • A2:D16: 15 orders with thin grey borders; amounts shown as #,##0.00.
  • Four pale yellow amounts: 2,140.00, 1,630.00, 1,990.00 and 1,725.00, the only ones above 1,500.
  • A small report in F1:G6: Rows 15, Address $A$2:$D$16, Cells 60, Total 16,035.00, Orders over 1,500: 4.
  • In the Immediate window (Ctrl+G): A2:D16 holds 60 cells.

Range in one sentence

Range takes the address you would type into the Name Box and hands back an object: something you can read from, write to, format, clear or ask questions. It can be one cell, a block, a whole column or row, or a named cell, and the address can be typed out or built from a variable:

Range("A1")              ' one cell
Range("A1:D16")          ' a block
Range("A1", "D16")       ' the same block, given as two corners
Range("D:D")             ' a whole column
Range("1:1")             ' a whole row
Range("D2:D" & lastRow)  ' an address built from a variable
Range("SalesTotal")      ' a named range (defined in Excel first)

Line by line: the six ideas in the macro

  1. ws.Range("A1:D1").Value = Array(โ€ฆ): one statement fills four cells. A range does not have to be a single cell to accept values.
  2. ws.Range("A" & i + 2): an address is just text, so you build it with &. When i is 0 this is A2; when it is 14, A16.
  3. Set data = ws.Range("A2", "D" & lastRow): the two-corner form (top-left, bottom-right) stored in a variable. Ranges are objects, and objects are assigned with Set.
  4. With ws.Range("A1:D1") โ€ฆ End With: several settings on the same block without repeating the address.
  5. For Each cell In amounts.Cells: visit every cell of a block, one at a time, and decide per cell.
  6. .Address, .Rows.Count, .Cells.Count: a range can describe itself, which is the quickest way to check that you built the block you meant.

Cheat sheet: what you can do with a range

  • .Value: read or write the contents (one cell, or a whole block at once).
  • .Formula: write a formula as text, e.g. "=SUM(D2:D16)".
  • .NumberFormat: change how a number looks, not the number itself.
  • .Font.Bold, .Font.Color, .Interior.Color, .Borders.Color: formatting.
  • .Address: the address as text, $A$2:$D$16; .Address(False, False) drops the dollar signs.
  • .Rows.Count, .Columns.Count, .Cells.Count: the size of the block.
  • .ClearContents: removes values only. .Clear: removes values and formatting.

Try it: three one-minute changes

1. Change Const LIMIT As Double = 1500 to 1000 and run again: now 7 amounts turn yellow and the report says so. 2. In the Immediate window type ?Range("A2", "D16").Cells.Count and press Enter: it answers 60 (15 rows ร— 4 columns). 3. Add amounts.ClearContents just before Debug.Print and run: the numbers vanish but the yellow stays, and the total in G5 drops to 0. Replace it with amounts.Clear and the yellow goes too.

Typical mistakes (everyone makes them once)

  • Forgetting Set: data = ws.Range("A2:D16") fails with Object variable or With block variable not set. Objects need Set data = โ€ฆ.
  • Forgetting the ampersand: "D2:D" lastRow is a syntax error; it has to be "D2:D" & lastRow.
  • A bare Range: Range("A1") without ws. means whichever sheet happens to be active. Fine for a quick test, a classic bug in a real macro.
  • Typing addresses that should move: Range("B4") keeps pointing at B4 after someone inserts a row above it. A defined name, Range("TaxRate"), follows the cell.

The trap: a comma makes two ranges, not one

Range("A2:A5,C2:C7") looks like a neat way to grab two blocks at once, and formatting really does reach all ten cells. But it is a multi-area range, and several properties quietly look at the first block only:

Dim multi As Range
Set multi = ws.Range("A2:A5,C2:C7")

Debug.Print multi.Areas.Count           ' 2  - two separate blocks
Debug.Print multi.Cells.Count           ' 10 - all ten cells
Debug.Print multi.Rows.Count            ' 4  - the FIRST block only, silently
Debug.Print multi.Areas(2).Rows.Count   ' 6  - the right way to ask

multi.Interior.Color = vbYellow         ' fine: colours all ten cells
multi.Copy ws.Range("H2")               ' stops with run-time error 1004
The silent line is the expensive one: .Rows.Count, .Row, .Column and .Value all describe the first area without any warning, so a loop sized by that count handles 4 rows and skips 6. Copying at least fails loudly. Use a comma for formatting only, and go through .Areas(1), .Areas(2) โ€ฆ whenever each block needs real work.

Where the course goes next

This lesson always wrote ws.Range(โ€ฆ) with letters. Next, Cells(row, column) lets you address by numbers, which is what loops really want. Then Selecting vs Referencing shows why the macro above never needed .Select, and Reading and Writing Values covers .Value, .Text and .Formula in depth. Later lessons move references with Offset and Resize and find the last used row instead of assuming it is 16.

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.

The data range A2:D16 as written by RangeTour (all names fictional)
RowA: OrderB: RegionC: CustomerD: AmountFill
21001NorthAlder Cafe420.00
31002SouthBirch Studio1,250.00
41003EastCedar Dental380.00
51004WestElm Bakery960.00
61005NorthFern Florist2,140.00yellow
71006EastGranite Gym515.00
81007SouthHarbor Books780.00
91008WestIris Optics1,630.00yellow
101009NorthJuniper Design290.00
111010EastKestrel Bikes1,105.00
121011SouthLinden Hotel870.00
131012WestMaple Garage1,990.00yellow
141013NorthNettle Tea Room640.00
151014EastOakwood Joinery1,340.00
161015SouthPine Clinic1,725.00yellow

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.

The report in F1:G6 and independent formula checks
Report lineVBA that fills itWorksheet formula checkResult
Rowsdata.Rows.Count=ROWS(A2:D16)15
Addressdata.Address=CELL("address",A2)&":"&CELL("address",D16)$A$2:$D$16
Cellsdata.Cells.Count=ROWS(A2:D16)*COLUMNS(A2:D16)60
Total"=SUM(" & amounts.Address & ")"=SUM(D2:D16)16,035.00
Orders over 1,500the counter bigOrders=COUNTIF(D2:D16,">1500")4
Average ordernot in the report=AVERAGE(D2:D16)1,069.00
North totalnot in the report=SUMIF(B2:B16,"North",D2:D16)3,490.00

Which range is which: the sheet RangeTour buildsABCDEFG12345678910111213141516A1:D1header, filled by one ArrayA2:D16Set data = Range("A2", "D16")D2:D16Set amounts, the For Each loop4 cellsValue > LIMIT, colouredF1:G6the report: .Address, .Count
A map of the generated sheet. Each coloured block is one Range object in the macro: the header A1:D1, the data range A2:D16, the amounts range D2:D16 with its four highlighted cells, and the report in F1:G6.

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.

The 15 orders in D2:D16 and the 1,500 limitAbove 1,500 (4 cells turn yellow)1,500 or less06001,2001,8002,400100110021003100410051006100710081009101010111012101310141015Order number (column A)LIMIT1,500
The amounts the macro writes into D2:D16. Butter-coloured bars are the four cells the For Each loop highlights because their value is greater than LIMIT (1,500).

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 + 2 works because VBA does the arithmetic first and then glues the result to the letter: when i is 3, the address is A5.
  • Range variables. Dim data As Range declares the variable, and Set fills it. After that, data is a short, readable name for A2:D16 on 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.Cells hands you one single-cell range at a time. In the lesson code the If is a block that also adds one to bigOrders; the one-line form above is shortened for reading.
  • Self-description. .Address, .Rows.Count and .Cells.Count are 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.

  1. Open a new workbook so nothing valuable can be overwritten.
  2. Press Alt+F11 to open the Visual Basic Editor (on a Mac: Tools โ†’ Macro โ†’ Visual Basic Editor).
  3. Choose Insert โ†’ Module and paste the RangeTour macro from the lesson into the empty code window.
  4. Open the Immediate window with Ctrl+G (Mac: View โ†’ Immediate Window). This is where Debug.Print writes.
  5. Click inside Sub RangeTour and press F5. The Immediate window shows A2:D16 holds 60 cells, and a message box reports the address and the total.
  6. Back in Excel, click into the Name Box (left of the formula bar), type A2:D16 and press Enter. Excel selects exactly the block that data refers to.
  7. Return to the editor, type ?ActiveSheet.Range("D2:D16").Address into the Immediate window and press Enter: $D$2:$D$16. Then try ?ActiveSheet.Range("D2:D16").Cells.Count: 15.
  8. To watch the loop work, click on the line For Each cell In amounts.Cells, press F9 to set a breakpoint, run the macro again and step with F8. Hover over cell.Value to see each amount in turn.
  9. 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.

Illustration for the VBA Ranges and Cells course: a worksheet with highlighted ranges and the matching VBA code
Ranges & Cells: point your code at exactly the cells you mean.

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") without Set stops 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" lastRow is 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") without ws. 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 as Range("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.Count silently returns 4, the size of the first area only. Symptom: a loop that stops halfway. Use .Areas when each block needs real work.
  • Value versus Text. .Value returns the stored number, .Text returns what the cell displays, including #### when the column is too narrow. Symptom: comparisons that fail only on some screens. Prefer .Value for logic.

Quick reference: range members and shortcuts

The members and keys used in this lesson, in one place:

Range members, worksheet functions and shortcuts used in this lesson
ItemKindWhat it does
Range("A2:D16")ObjectA block of cells by address
Range("A2", "D16")ObjectThe same block given by two corner cells
Cells(r, c)ObjectOne cell by row and column number
.Value / .FormulaPropertyStored content / formula text
.NumberFormatPropertyHow a number is displayed, e.g. "#,##0.00"
.Interior.Color, .Font.BoldPropertyFill colour, bold text
.Address, .Address(False, False)Property$A$2:$D$16 or A2:D16
.Rows.Count, .Cells.CountPropertySize of the block
.ClearContents / .ClearMethodRemove values only / values and formats
.AreasPropertyThe separate blocks of a multi-area range
ROWS, COLUMNS, SUM, COUNTIF, SUMIFWorksheet functionsCheck the macro's report independently
Alt+F11, F5, F8, F9, Ctrl+GShortcutsEditor, 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 Each loop over the amount column does it, and a counter tells the reviewer how many there are, just like bigOrders in 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").ClearContents on a defined name does it safely.
  • Region summaries. A sales lead needs totals per region in a fixed layout. The macro writes SUMIF formulas whose ranges come from range variables, which gives the figures shown in the chart below.

Order value by region (what SUMIF returns)01,0002,0003,0004,0005,000South4,625West4,580North3,490East3,340
Order value by region for the lesson data, as =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 $9.90.

  1. Cells(row, column)
  2. Selecting vs Referencing
  3. Reading and Writing Values
  4. Moving Around with Offset and Resize
  5. CurrentRegion and UsedRange
  6. Finding the Last Row
  7. Being Explicit About the Sheet

Buy course โ€” $9.90 See the full course

Knowledge check

Set r = ws.Range("A2:A5,C2:C7"). What does r.Rows.Count return?

Continues in this course
  • Cells(row, column)
  • Selecting vs Referencing
  • Reading and Writing Values
  • Moving Around with Offset and Resize
  • CurrentRegion and UsedRange
  • Finding the Last Row

Buy the course to unlock the remaining 7 lessons, the exam and the certificate.

Buy course โ€” $9.90