In Excel VBA, Range is an object type: it represents one cell, a group of cells, or a larger range on a worksheet. Declare a variable with As Range and use Set to assign it a cell or range object; the object’s properties, such as Value and Address, let your code inspect or change worksheet cells.
What the VBA Range Type Represents
Range is part of Excel’s object model, not a basic value type like Long, String, or Boolean. A Range object is a reference to cells in a worksheet. It can represent a single cell, a rectangular block, complete rows or columns, or multiple separate areas. For example, a reference might point to cell A1, cells A1 through C10, or two nonadjacent blocks.
This distinction matters because a Range variable does not itself contain the cell’s value. It points to the cell or cells. To read or change cell content, use a property such as Value or Value2. To find where the object points, use a property such as Address. The same range can also expose formatting, formulas, and other worksheet features.
There is a possible source of confusion in VBA: the keyword Type can also appear in a Type ... End Type declaration for a user-defined data structure. That is unrelated to the Excel Range object. In a variable declaration, As Range means the variable is intended to refer to an Excel Range object.
Declaring and Assigning a Range Variable
Declare a Range variable with Dim. Because a range is an object, assign the reference with VBA’s Set statement. This is different from assigning a number or text value to a variable. For example, a variable declared as Long receives a numeric value directly, while a Range variable must be set to an actual range object.
The distinction between an object reference and a cell value is important in everyday code. Use Set when the variable is being made to refer to cells. Do not use Set when putting a value into cells through the range’s Value property. A common pattern is to declare a range variable, point it to a worksheet range, and then read or change that range through its properties.
It is also possible to declare a variable as Object or Variant, but As Range is usually clearer when the variable is meant to refer to Excel cells. The specific type documents the code’s purpose and gives VBA and the editor more information about the object’s available members.
Qualifying a Range with Its Worksheet
A range reference belongs to a worksheet. If code uses an unqualified Range reference, VBA generally resolves it against the active sheet. That can make a macro behave differently depending on which worksheet the user has selected. It can also produce a wrong result without an obvious error if the active sheet happens to contain similarly arranged data.
For dependable code, qualify the range with the worksheet it belongs to. In a workbook macro, a worksheet variable is a convenient way to do that. Choose the workbook reference deliberately: ThisWorkbook means the workbook containing the VBA code, while ActiveWorkbook means the workbook currently active in Excel. They are not always the same, for example when code is stored in the Personal Macro Workbook.
When identifying a worksheet by name, the name must match a worksheet tab in the workbook. A misspelled or missing sheet name causes a runtime error. A useful habit is to assign the worksheet first and then build the range from that worksheet, rather than relying on the active selection.
Reading Values and Working with Multiple Cells
A single-cell Range’s Value property usually returns a Variant containing the cell’s value. With a multi-cell range, reading Value or Value2 generally returns a two-dimensional Variant array. This is why code that expects a single value can behave unexpectedly when the referenced range expands to several cells.
Value2 is commonly used when transferring values between cells and VBA. Unlike Value, it does not use VBA’s Currency and Date subtypes for certain cell values; date and currency-formatted numbers are returned as their underlying numeric values. Excel stores dates as serial numbers, so interpreting a number as a date may require attention to the cell’s format or the application’s date-handling logic. The Text property is different again: it gives the displayed, formatted text and is generally read-only.
For a large block of cells, reading the range into an array, processing the array in memory, and writing it back can be more efficient than repeatedly asking Excel for individual cell values. The trade-off is that the code must handle the array’s dimensions and account for empty cells, errors, and values of different kinds.
Choosing Between Range, Cells, and Other References
Use Range when the address is known or when a readable block reference makes the code easiest to understand. Use Cells when row and column numbers are calculated, such as in a loop. Both approaches return Range objects, so a variable declared as Range can hold the result of either.
For example, a loop that advances through rows can use numeric row and column positions with Cells. A block specified by familiar worksheet addresses may be more readable as a Range reference. The Cells property is also useful as a starting point for building a range whose boundaries change as the data grows.
A Range can include more than one area. Excel’s Union method can combine separate ranges into a single Range object, and a comma-separated address can also describe multiple areas. Be aware that some operations behave differently on multi-area ranges, and code that assumes a single rectangle may need to check the range’s areas before processing it.
A Practical Macro Example
This example formats a fixed block on a worksheet named Data. The worksheet and target are both declared with their specific object types, and the target is explicitly qualified so the active sheet does not determine where the formatting is applied.
Sub HighlightDataBlock()
' Save a copy of the workbook before running this macro.
Dim ws As Worksheet
Dim target As Range
Set ws = ThisWorkbook.Worksheets("Data")
Set target = ws.Range("B2:B10")
target.Interior.Color = RGB(255, 255, 0)
End Sub
The macro changes cell formatting, so save a copy of the workbook before running it. VBA macros cannot be undone with Ctrl+Z. If the intended workbook is not the one containing the macro, change the workbook reference deliberately rather than assuming ThisWorkbook points to the file currently being edited.
In Excel for Microsoft 365 on Windows, the Visual Basic Editor can be opened with Alt+F11. On a Mac, Option+F11 may work, sometimes with the Fn key depending on keyboard settings; the Developer tab’s Visual Basic command is an alternative when available. The VBA object model is similar on Mac, though some Windows-specific automation features are not supported there.
Common Range Type Problems
Several frequent mistakes come from treating a Range object like a value or leaving its worksheet context implicit. When VBA reports an object-related error, check what the variable refers to and whether the referenced workbook and worksheet actually exist.
- Missing
Set: UseSetto assign an object reference to a Range variable. Assign a cell’s contents through a property such asValue, withoutSet. - Wrong active sheet: An unqualified range can point to the active worksheet. Qualify it with the intended worksheet object.
- Object variable not set: A declared Range variable has no usable target until it has been assigned an object. Trying to access its properties too soon can cause an error.
- Single value versus array: A multi-cell range does not return the same shape of result as a single cell. Check whether the code expects a scalar or a two-dimensional array.
- Unexpected worksheet name: Confirm the tab name and the workbook reference. A sheet in another workbook is not found through the wrong workbook object.
- Using
Nothingas a cell value:Nothingmeans an object variable has no object reference. It is not a value to put into a worksheet cell.
Range variables are normally cleaned up automatically when they go out of scope. Setting one to Nothing can be useful when deliberately releasing an object reference earlier, but it is not required after every ordinary use. Focus first on assigning the right object and qualifying it correctly.
Range Compared with Variant and Cell Values
Range and Variant serve different roles. A Range variable refers to cells; a Variant can hold many kinds of values, including a number, text, an error value, or an array. A cell’s Value property commonly returns a Variant because worksheet cells can contain different types of content.
For example, a macro might use a Range variable to identify a column and a Variant array to hold the values read from that column. The Range represents the location in Excel; the array represents data copied into VBA memory. Confusing those roles can lead to assignment errors or code that fails when the range contains multiple cells.
Use a specific type such as Range for a known Excel object, and use a suitable value type for the data being processed when its type is known. A Variant is flexible and can be useful for mixed worksheet data, but that flexibility makes it important to check what it contains before doing calculations or string operations.
Frequently Asked Questions
Is Range a data type in VBA?
It is an object type in Excel VBA, not a basic scalar type like Integer or String. A variable declared as Range refers to cells and their associated properties and methods.
Why does a Range variable need Set?
A Range variable stores a reference to an object. VBA uses Set to assign object references. To assign cell content, use a property such as Value instead.
Does Range refer to the active worksheet?
An unqualified Range reference generally uses the active sheet. Qualifying the reference with a worksheet is safer because it makes the target explicit and avoids depending on the user’s current selection.
What is the difference between Range and Cells?
Both can identify cells and return Range objects. Range is convenient for address-based references such as a named block; Cells is useful when row and column numbers are calculated, such as in a loop.
Should I use Value or Value2?
Both access cell values. Value2 avoids converting certain values to VBA Date or Currency subtypes, so it is often convenient for data transfer. If your code needs dates or currency interpreted as those types, consider how the conversion should be handled.
Can a Range variable refer to more than one cell?
Yes. It can refer to a rectangular block or multiple areas. When reading a multi-cell range, expect a two-dimensional array in many cases rather than a single cell value.
Related
- Freeze Panes in Excel: Keep Rows and Columns Visible
- Find Duplicates in Excel: A Practical Step-by-Step Guide
- How to Find External Links in Excel and Check Their Sources
Try it: the Column Letter to Number: aA is 27, XFD is 16,384. Converts both ways.
More in VBA & macros
- Delete Entire Row VBA: Examples and Safety TipsTo delete a complete worksheet row with VBA, use Rows(rowNumber).Delete on a specifically named worksheet, such as Worksheets("Data").Rows(5).Delete.…
- How to Put a Photo in a VBA UserFormTo put a photo in an Excel VBA UserForm, add an Image control, then either set its Picture…
- VBA Loop Code: Examples for Excel MacrosVBA loop code repeats an instruction for a set number of times, for each item in a collection,…
- Access VBA String to Number: Safe Conversion GuideIn Access VBA, convert a numeric string with the function that matches the number you need: use CLng…
- Excel Macro Filter: How to Automate Data FilteringTo filter a worksheet with a macro, use VBA’s AutoFilter method on a range that includes its header…
- VBA Copy and Paste Range in ExcelTo copy an Excel range with VBA, use sourceRange.Copy Destination:=destinationCell; Excel copies the cells to the destination, including…
Sources: Function behaviour and menu paths: Microsoft Support documentation for Excel. Method & sources
Spotted an error in this guide? Let us know.