- The Range Object
- Syntax to Specify a Range
- Named Ranges
- Shortcut for Referencing Ranges
- Referencing Ranges in Other Sheets
- Referencing a Range Relative to Another Range
- Use the Cells Property to Select a Range
- Use the Offset Property to Refer to a Range
- Use the Resize Property to Change the Size of a Range
- Use the Columns and Rows Properties to Specify a Range
- Use the Union Method to Join Multiple Ranges
- Use the Intersect Method to Create a New Range from Overlapping Ranges
- Use the ISEMPTY Function to Check Whether a Cell Is Empty
- Use the CurrentRegion Property to Select a Data Range
- Use the Areas Collection to Return a Noncontiguous Range
- Referencing Tables
- Next Steps
Use the Cells Property to Select a Range
The Cells property refers to all the cells of the specified range object, which can be a worksheet or a range of cells. For example, this line selects all the cells of the active sheet:
Using the Cells property with the Range object might seem redundant:
This line refers to the original Range object. However, the Cells property has an Item property that makes the Cells property very useful. The Item property enables you to refer to a specific cell relative to the Range object.
The syntax for using the Item property with the Cells property is as follows:
You must use a numeric value for Row, but you may use the numeric value or string value for Column. Both of the following lines refer to cell C5:
Because the Item property is the default property of the RANGE object, you can shorten these lines as follows:
The ability to use numeric values for parameters is particularly useful if you need to loop through rows or columns. The macro recorder usually uses something like Range("A1"). Select for a single cell and Range("A1:C5").Select for a range of cells. If you are learning to code only from the recorder, you might be tempted to write code like this:
FinalRow = Cells(Rows.Count, 1).End(xlUp).Row For i = 1 to FinalRow Range("A" & i & ":E" & i).Font.Bold = True Next i
This little piece of code, which loops through rows and bolds the cells in Columns A through E, is awkward to read and write. But, how else can you do it?
FinalRow = Cells(Rows.Count, 1).End(xlUp).Row For i = 1 to FinalRow Cells(i,"A").Resize(,5).Font.Bold = True Next i
Instead of trying to type the range address, the new code uses the Cells and Resize properties to find the required cell, based on the active cell. See the “Use the Resize Property to Change the Size of a Range” section later in this chapter for more information on the Resize property.
Cells properties can be used as parameters in the Range property. The following refers to the range A1:E5:
This is particularly useful when you need to specify your variables with a parameter, as in the previous looping example.