In VBA, you set a range of cells by using the Range or Cells property, for example Set myRange = Range("A1:C10") or Set myRange = Range(Cells(1,1), Cells(10,3)). The Set keyword is required when assigning an object (like a Range) to a variable, and it lets you refer to that block of cells by name throughout your macro.
Why You Need the Set Keyword
In VBA, there are two kinds of assignments: value assignments and object assignments. When you write x = 5, you’re storing a number. But a Range is an object—it has properties and methods. To store a reference to an object, you must use Set. Forgetting Set is one of the most common VBA errors; it triggers a “Object required” runtime error (Error 424).
Example of correct and incorrect syntax:
' Correct
Dim rng As Range
Set rng = Range("A1:B2")
' Incorrect - causes error 424
Dim rng2 As Range
rng2 = Range("A1:B2") ' Missing Set
Basic Ways to Set a Range
There are several ways to reference a range in VBA, and the best one depends on what you’re doing.
- Using the Range property with an address string:
Set rng = Range("A1:D10")– simple and readable. - Using the Cells property with row and column numbers:
Set rng = Range(Cells(1,1), Cells(10,4))– useful when you need to calculate positions dynamically. - Using a named range:
Set rng = Range("MyNamedRange")– works if you’ve defined a name in the workbook. - Using the ActiveSheet or Worksheets:
Set rng = Worksheets("Sheet1").Range("A1:C3")– always specify the sheet to avoid surprises.
Note: If you omit the sheet qualifier, VBA uses the active sheet. That can cause bugs if the user switches sheets while your macro runs.
Setting a Range with Cells: Dynamic References
The Cells property returns a single cell, but you can combine two Cells to define a rectangular range. This is especially powerful in loops where row and column numbers change.
Example: Suppose you want to select the first 5 rows and first 3 columns of the used range. You could write:
Dim firstCell As Range, lastCell As Range
Set firstCell = Cells(1, 1)
Set lastCell = Cells(5, 3)
Set rng = Range(firstCell, lastCell)
This is equivalent to Range("A1:C5"), but you can compute the numbers. For instance, to reference a block starting at row 2, column 1, with 10 rows and 4 columns:
Dim startRow As Long, startCol As Long, numRows As Long, numCols As Long
startRow = 2: startCol = 1: numRows = 10: numCols = 4
Set rng = Range(Cells(startRow, startCol), Cells(startRow + numRows - 1, startCol + numCols - 1))
Common Pitfalls and How to Avoid Them
Even experienced VBA developers hit these issues regularly.
- Using Range without a sheet qualifier: Always write
Worksheets("Data").Range(...)orActiveSheet.Range(...)if you intend the active sheet. Otherwise, your code may operate on the wrong sheet. - Mixing up row and column in Cells:
Cells(1,1)is row 1, column 1 (A1).Cells(2,1)is A2. The first argument is always the row. - Assuming a range is contiguous: The
Rangeproperty can also handle multiple areas, e.g.,Range("A1:A5, C1:C5"). ButSetstill works; just remember that some methods (like.Value) treat it as an array. - Forgetting that Range is an object: If you try to assign a range to a variable without
Set, you’ll get an error. Always useSetfor object variables.
Working with the Range Object After Setting It
Once you’ve set a range, you can do many things with it. Here are a few common operations:
- Read or write values:
rng.Value = 42writes 42 to every cell in the range.Dim v As Variant: v = rng.Valuereads a 2D array if the range has multiple cells. - Format cells:
rng.Font.Bold = Trueorrng.Interior.Color = RGB(255,0,0). - Resize the range:
Set rng2 = rng.Resize(5, 5)returns a new range that is 5 rows by 5 columns, starting at the top-left of rng. - Offset the range:
Set rng3 = rng.Offset(1, 0)moves down one row. - Clear or delete:
rng.Clearclears contents and formatting;rng.Deleteshifts cells.
Example that sets a range, writes a formula, and formats it:
Dim rng As Range
Set rng = Range("B2:B10")
rng.Formula = "=A2*2" ' fills each cell with a relative formula
rng.Font.Bold = True
rng.NumberFormat = "0.00"
Alternatives to Range: Cells, Rows, Columns, and Union
Sometimes you don’t need a full range variable. You can use Cells directly, or work with entire rows and columns.
- Single cell:
Cells(1,1).Value = "Hello"– no need to set a range. - Entire row:
Rows(3).SelectorSet rng = Rows(3). - Entire column:
Columns("B").SelectorSet rng = Columns(2). - Non-contiguous ranges: Use
Unionto combine multiple areas:Set rng = Union(Range("A1:A5"), Range("C1:C5")).
These are useful when you want to apply an operation to a whole row or column, or when you need to work with multiple separate blocks.
Frequently Asked Questions
How do I set a range to a variable in VBA?
Use the Set keyword with the Range property. For example: Dim myRange As Range: Set myRange = Range("A1:B2"). Always declare the variable as Range and use Set; otherwise you’ll get an error.
What is the difference between Range and Cells in VBA?
Range returns a range object that can represent one cell or a block of cells, and you can pass a string like “A1:B2”. Cells returns a single cell based on row and column numbers. You can combine them: Range(Cells(1,1), Cells(2,2)) gives the same as Range("A1:B2").
Why do I get “Object required” error when setting a range?
That error usually means you forgot the Set keyword. For example, myRange = Range("A1") is wrong; it must be Set myRange = Range("A1"). Also, make sure the variable is declared as Range.
How do I set a range to the used range of a worksheet?
Use Set rng = ActiveSheet.UsedRange or Worksheets("Sheet1").UsedRange. This returns a range that includes all cells that have ever been used (formatted or with data).
Can I set a range that is not contiguous?
Yes, you can use the Union function: Set rng = Union(Range("A1:A5"), Range("C1:C5")). This creates a multi-area range. Note that some methods, like .Value, work differently on multi-area ranges, so test carefully.
Best Practices for Using Set Range
To write reliable VBA code, follow these tips:
- Always qualify ranges with a worksheet:
Worksheets("Data").Range("A1")instead of justRange("A1"). - Use meaningful variable names:
Set dataRangeis better thanSet r. - Release object references when done: Set
rng = Nothingat the end of your macro to free memory, especially in long loops. - Save a backup before running macros: Since macros cannot be undone with Ctrl+Z, always save a copy of your workbook before testing code that modifies data.
- Use Option Explicit: This forces you to declare all variables, catching typos early.
By mastering Set Range, you’ll be able to write macros that manipulate cells efficiently and correctly.
Related
- Hitachi Magnetic Driver Bits: What to Know
- Google Sheets XLOOKUP: How to Use It
- Chapter 7 Traffic Signs Manual: Full Guide
Try it: the Column Letter to Number: aA is 27, XFD is 16,384. Converts both ways.
More in VBA & macros
- String in VBA: Meaning, Types, and Practical ExamplesIn VBA, String is the data type used to store text, such as names, messages, codes, and text…
- Excel VBA Data Entry Form With a Picture Box: How It WorksYes. In Excel for Microsoft 365 on Windows, make a VBA UserForm, add an Image control to act…
- Excel VBA: How to Check Whether Cell Colors Match ExactlyYes. In Excel VBA, compare the cells’ Interior.Color values; they are numeric color values, so an equality test…
- Excel VBA Get Year From Date: Code, Dates, and ErrorsTo get the year from a date in Excel VBA, use the built-in Year function: Year(dateValue). For example,…
- VBA AutoFilter Syntax: Criteria, Fields, and ExamplesIn Excel VBA, the basic AutoFilter syntax is Range.AutoFilter Field:=columnNumber, Criteria1:=value. The range should include the list’s header…
- How to Activate Macros in Excel (Step-by-Step)Activating macros in Excel lets you run automated tasks written in VBA (Visual Basic for Applications), such as…
Sources: Function behaviour and menu paths: Microsoft Support documentation for Excel. Method & sources
Spotted an error in this guide? Let us know.