The Range Object
Lesson 1 of 8 ยท 6 min
One object for one cell or a million
Range is how VBA refers to cells. You hand it the same address you would type in the Name Box, and you get back an object you can read from, write to, format or clear. A Range can be a single cell, a block, an entire column, or several separate areas at once.
Range("A1") ' one cell
Range("A1:C10") ' a block
Range("A:A") ' a whole column
Range("3:3") ' a whole row
Range("A1:A5,C1:C5") ' two separate areas
Range("SalesTotal") ' a named rangeTwo corners instead of a string
Range also accepts two arguments โ a top-left and a bottom-right cell โ which is far more useful once those corners come from variables:
Sub TwoCornerRange()
Dim lastRow As Long
lastRow = 250
Range("A2", Range("D" & lastRow)).Interior.Color = vbYellow
End SubBuilding an address from a variable
Because the address is just text, you can build it with the ampersand. This is the everyday way to point at a row whose number your code worked out:
Dim r As Long
r = 7
Range("B" & r).Value = "Row seven" ' writes to B7Things you can do to a Range
- .Value โ read or write the contents.
- .Formula โ read or write a formula as text.
- .ClearContents โ wipe values, keep formatting.
- .Clear โ wipe everything, formatting included.
- .Copy and .Delete โ exactly what they sound like.
- .Rows.Count and .Columns.Count โ how big it is.
Watch the quotation marks
Range("A1") with quotes is a cell address. Range(A1) without them makes VBA look for a variable named A1, which under Option Explicit gives you an immediate error โ and without it, a silent failure. The quotes are not optional.
A range can describe itself
Every range knows its own address and size. Debug.Print Range("A1:C3").Address returns $A$1:$C$3, while .Rows.Count, .Columns.Count and .Cells.Count report its dimensions. These are invaluable when you build a range out of variables: print the address in the Immediate window and you can see instantly whether you got the block you intended.
Range("TaxRate"). If someone inserts a row, the name follows the cell and your macro keeps working.Range("A1:A5,C1:C5") refer to?Sign in to answer and track your progress.
Sign in- ๐ Cells(row, column) 6 min
- ๐ Selecting vs Referencing 7 min
- ๐ Reading and Writing Values 7 min
- ๐ Moving Around with Offset and Resize 6 min
- ๐ CurrentRegion and UsedRange 7 min
- ๐ Finding the Last Row 7 min
- ๐ Being Explicit About the Sheet 6 min
Pro unlocks these 7 lessons, the final exam and the certificate โ plus every other course.
Unlock all lessons