Range Collection [Excel 2003 VBA Language Reference] (2024)

  • Article

Multiple objects
Range Collection [Excel 2003 VBA Language Reference] (1)Range
Range Collection [Excel 2003 VBA Language Reference] (2)Range Collection [Excel 2003 VBA Language Reference] (3)Multiple objects

Represents a cell, a row, a column, a selection of cells containing one or more contiguous blocks of cells, or a 3-D range.

Using the Range Collection

The following properties and methods for returning a Range object are described in this section:

  • Range property
  • Cells property
  • Range and Cells
  • Offset property
  • Union method

Range Property

Use Range(arg), where arg names the range, to return a Range object that represents a single cell or a range of cells. The following example places the value of cell A1 in cell A5.

Worksheets("Sheet1").Range("A5").Value = _ Worksheets("Sheet1").Range("A1").Value

The following example fills the range A1:H8 with random numbers by setting the formula for each cell in the range. When it's used without an object qualifier (an object to the left of the period), the Range property returns a range on the active sheet. If the active sheet isn't a worksheet, the method fails. Use the Activate method to activate a worksheet before you use the Range property without an explicit object qualifier.

Worksheets("Sheet1").ActivateRange("A1:H8").Formula = "=Rand()" 'Range is on the active sheet

The following example clears the contents of the range named Criteria.

Worksheets(1).Range("Criteria").ClearContents

If you use a text argument for the range address, you must specify the address in A1-style notation (you cannot use R1C1-style notation).

Cells Property

Use Cells(row, column) where row is the row index and column is the column index, to return a single cell. The following example sets the value of cell A1 to 24.

Worksheets(1).Cells(1, 1).Value = 24

The following example sets the formula for cell A2.

ActiveSheet.Cells(2, 1).Formula = "=Sum(B1:B5)"

Although you can also use Range("A1") to return cell A1, there may be times when the Cells property is more convenient because you can use a variable for the row or column. The following example creates column and row headings on Sheet1. Notice that after the worksheet has been activated, the Cells property can be used without an explicit sheet declaration (it returns a cell on the active sheet).

Sub SetUpTable()Worksheets("Sheet1").ActivateFor TheYear = 1 To 5 Cells(1, TheYear + 1).Value = 1990 + TheYearNext TheYearFor TheQuarter = 1 To 4 Cells(TheQuarter + 1, 1).Value = "Q" & TheQuarterNext TheQuarterEnd Sub

Although you could use Visual Basic string functions to alter A1-style references, it's much easier (and much better programming practice) to use the Cells(1, 1) notation.

Use expression.Cells(row, column) , where expression is an expression that returns a Range object, and row and column are relative to the upper-left corner of the range, to return part of a range. The following example sets the formula for cell C5.

Worksheets(1).Range("C5:C10").Cells(1, 1).Formula = "=Rand()"

Range and Cells

Use Range(cell1, cell2), where cell1 and cell2 are Range objects that specify the start and end cells, to return a Range object. The following example sets the border line style for cells A1:J10.

With Worksheets(1) .Range(.Cells(1, 1), _ .Cells(10, 10)).Borders.LineStyle = xlThickEnd With

Notice the period in front of each occurrence of the Cells property. The period is required if the result of the preceding With statement is to be applied to the Cells property — in this case, to indicate that the cells are on worksheet one (without the period, the Cells property would return cells on the active sheet).

Offset Property

Use Offset(row, column), where row and column are the row and column offsets, to return a range at a specified offset to another range. The following example selects the cell three rows down from and one column to the right of the cell in the upper-left corner of the current selection. You cannot select a cell that isn't on the active sheet, so you must first activate the worksheet.

Worksheets("Sheet1").Activate 'Can't select unless the sheet is activeSelection.Offset(3, 1).Range("A1").Select

Union Method

Use Union(range1, range2, ...) to return multiple-area ranges — that is, ranges composed of two or more contiguous blocks of cells. The following example creates an object defined as the union of ranges A1:B2 and C3:D4, and then selects the defined range.

Dim r1 As Range, r2 As Range, myMultiAreaRange As RangeWorksheets("sheet1").ActivateSet r1 = Range("A1:B2")Set r2 = Range("C3:D4")Set myMultiAreaRange = Union(r1, r2)myMultiAreaRange.Select

If you work with selections that contain more than one area, the Areas property is very useful. It divides a multiple-area selection into individual Range objects and then returns the objects as a collection. You can use the Count property on the returned collection to check for a selection that contains more than one area, as shown in the following example.

Sub NoMultiAreaSelection() NumberOfSelectedAreas = Selection.Areas.Count If NumberOfSelectedAreas > 1 Then MsgBox "You cannot carry out this command " & _ "on multi-area selections" End IfEnd Sub

Properties | AddIndent Property | Address Property | AddressLocal Property | AllowEdit Property | Application Property | Areas Property | Borders Property | Cells Property | Characters Property | Column Property | Columns Property | ColumnWidth Property | Comment Property | Count Property | Creator Property | CurrentArray Property | CurrentRegion Property | Dependents Property | DirectDependents Property | DirectPrecedents Property | End Property | EntireColumn Property | EntireRow Property | Errors Property | Font Property | FormatConditions Property | Formula Property | FormulaArray Property | FormulaHidden Property | FormulaLabel Property | FormulaLocal Property | FormulaR1C1 Property | FormulaR1C1Local Property | HasArray Property | HasFormula Property | Height Property | Hidden Property | HorizontalAlignment Property | Hyperlinks Property | ID Property | IndentLevel Property | Interior Property | Item Property | Left Property | ListHeaderRows Property | ListObject Property | LocationInTable Property | Locked Property | MergeArea Property | MergeCells Property | Name Property | Next Property | NumberFormat Property | NumberFormatLocal Property | Offset Property | Orientation Property | OutlineLevel Property | PageBreak Property | Parent Property | Phonetic Property | Phonetics Property | PivotCell Property | PivotField Property | PivotItem Property | PivotTable Property | Precedents Property | PrefixCharacter Property | Previous Property | QueryTable Property | Range Property | ReadingOrder Property | Resize Property | Row Property | RowHeight Property | Rows Property | ShowDetail Property | ShrinkToFit Property | SmartTags Property | SoundNote Property | Style Property | Summary Property | Text Property | Top Property | UseStandardHeight Property | UseStandardWidth Property | Validation Property | Value Property | Value2 Property | VerticalAlignment Property | Width Property | Worksheet Property | WrapText Property | XPath Property

Methods | Activate Method | AddComment Method | AdvancedFilter Method | ApplyNames Method | ApplyOutlineStyles Method | AutoComplete Method | AutoFill Method | AutoFilter Method | AutoFit Method | AutoFormat Method | AutoOutline Method | BorderAround Method | Calculate Method | CheckSpelling Method | Clear Method | ClearComments Method | ClearContents Method | ClearFormats Method | ClearNotes Method | ClearOutline Method | ColumnDifferences Method | Consolidate Method | Copy Method | CopyFromRecordset Method | CopyPicture Method | CreateNames Method | CreatePublisher Method | Cut Method | DataSeries Method | Delete Method | DialogBox Method | Dirty Method | EditionOptions Method | FillDown Method | FillLeft Method | FillRight Method | FillUp Method | Find Method | FindNext Method | FindPrevious Method | FunctionWizard Method | GoalSeek Method | Group Method | Insert Method | InsertIndent Method | Justify Method | ListNames Method | Merge Method | NavigateArrow Method | NoteText Method | Parse Method | PasteSpecial Method | PrintOut Method | PrintPreview Method | RemoveSubtotal Method | Replace Method | RowDifferences Method | Run Method | Select Method | SetPhonetic Method | Show Method | ShowDependents Method | ShowErrors Method | ShowPrecedents Method | Sort Method | SortSpecial Method | Speak Method | SpecialCells Method | SubscribeTo Method | Subtotal Method | Table Method | TextToColumns Method | Ungroup Method | UnMerge Method

Parent Objects | AllowEditRange Object | Application Object | Areas Collection | AutoFilter Object | ChartObject Object | HPageBreak Object | Hyperlink Object | ListColumn Object | ListObject Object | ListRow Object | Name Object | OLEObject Object | Pane Object | Parameter Object | PivotCell Object | PivotField Object | PivotItem Object | PivotTable Object | QueryTable Object | Range Collection | Scenario Object | Shape Object | SmartTag Object | VPageBreak Object | Window Object | Worksheet Object

Child Objects | Areas Object | Borders Object | Characters Object | Comment Object | Errors Object | Font Object | FormatConditions Object | Hyperlinks Object | Interior Object | ListObject Object | Phonetic Object | Phonetics Object | PivotCell Object | PivotField Object | PivotItem Object | PivotTable Object | QueryTable Object | Range Object | SmartTags Object | SoundNote Object | Validation Object | Worksheet Object | XPath Object

Range Collection [Excel 2003 VBA Language Reference] (2024)

FAQs

How do I reference a range of cells in Excel VBA? ›

VBA Cell References – Selecting Ranges or Cells
  1. Selecting one cell: Range(“B5”)
  2. Selecting one range: Range(“B5:D5”)
  3. Selecting multiple ranges and cells: Range(“B5:D5,E10:J50,M99”)
  4. Selecting the active cell (whatever is currently selected in the Excel file): ActiveCell.

How to specify range in Excel VBA? ›

First, define the variable as the “Range” object. Once we define the variable as the “Range” object, we need to set the reference for this variable about what the cell addresses will hold the reference to. To set the reference, we need to use the “SET” keyword and enter the cell addresses using the RANGE object.

How to check range values in VBA? ›

In the VBA editor go to the View menu and click on Locals Window. Each time F8 is pressed one line of VBA is executed. When the range MyRange is set, you can see that values appear for it in the Locals window. By examining the MyRange object you can drill down to see the values in it.

How do you pass a cell range in VBA? ›

To copy and paste a range in Excel VBA, you use the Copy and Paste methods. The Copy method copies a range, and the Paste method pastes it into a worksheet. It might look a bit complicated but let's see what each does with an example below.

What is the correct way to reference a range of cells in Excel? ›

What is a range reference in Excel? In Microsoft Excel, a range is a block of two or more cells. A range reference is represented by the address of the upper left cell and the lower right cell separated with a colon. For example, the range A1:C2 includes 6 cells from A1 through C2.

What is the difference between cell reference and cell range? ›

The main difference between the two cells is what they reference. Cells usually reference a single cell at a time, while Range references a group of cells at once. The format for this function is Cells(row, column).

How do you reference a range sheet in Excel? ›

  1. Click the tab for the first worksheet that you want to reference.
  2. Hold down SHIFT and click the tab for the last worksheet that you want to reference.
  3. Select the cell or range of cells that you want to reference.
  4. Complete the formula, and then press ENTER.

How do I select a data range in Excel VBA? ›

To manually select all the data in a column, select the first cell, and press CTRL+SHIFT+DOWN ARROW. Likewise, to manually select a row and all columns attached to the row, press CTRL+SHIFT+DOWN ARROW+RIGHT ARROW. However, all data must be contiguous (that is, you cannot have blank rows or columns).

How do I select a range dynamically in Excel VBA? ›

By utilizing the range object and cells object, the dynamic ranges in Excel VBA can be defined and created. There are many ways in which dynamic ranges can be created. Following are the methods listed below: Variable initialization to the range and cell object.

How do I filter a range of values in VBA? ›

Examples to Filter Data using VBA
  1. Step 1: Supply data range. To activate the filter option first, we need to supply what is our data range. ...
  2. Step 2: Then access AutoFilter function. Now, access the AutoFilter function for this range. ...
  3. Step 3: Run the code to enable the filter. That is all.
Jan 1, 2024

How do I set a range variable in VBA? ›

Declare a Range Variable in VBA

First of all, use the Dim keyword and enter the name of the variable. In our example, we are using the name rng . After that, enter the keyword, as to get the list of the data types and declare the data type as Range. And then type the name of the variable.

How do you get the value from a range of cells in Excel? ›

If you want to retrieve values from a range of cells, use the GetRange and GetRangeA1 methods instead. Methods that have the A1 suffix ( GetCellA1 and GetRangeA1) use a different coordinate system than those that do not ( GetCell and GetRange).

How to use range in VBA code? ›

For example, the range property in VBA is used to refer to specific rows or columns while writing the code. The code “Range(“A1:A5”). Value=2” returns the number 2 in the range A1:A5.

What is the difference between range and cells in VBA? ›

In VBA, Range is an object, but Cell is a property in an excel sheet. In VBA, we have two ways of referencing a cell object one through Range, and another one is through Cells. For example, if you want to reference cell C5, you can use two methods to refer to the cell C5.

What is an example of a range in Excel? ›

A cell range can be used inside a formula, for example to calculate the sum of the values within the selected cells. The notation for the sum of all values in cell range (A1:C6) is =SUM(A1:C6).

How do you reference a cell named range in VBA? ›

Excel VBA Named Range. We can select a cell or range of cells and name it. Then, after naming the cells, we can refer to those cells by entering those defined names instead of the usual row or column references.

How to reference a cell value in VBA Excel? ›

Technically, there are two methods to interact with a cell in VBA: the range method and the cell method. We can use the range method like range(“A2”). The value will give us the value of the A2 cell, or we can use the cell method as cells(2,1). The value will also give us the value of A2 cells.

How do cells() work in VBA? ›

Every worksheet in Excel has a Cells property in VBA. You use Cells() to refer to Single cells on the worksheet, or All cells on the worksheet. The differences between Range and Cells: Cells refers to Single cells only – it can't refer to multiple cells like Range (“A1:E5”)

How do you go through each cell in a range in VBA? ›

We do this with Excel VBA with the help of the For Each Collection loop. This allows us to loop through each cell inside the used range of the worksheet and, with the help of the IF statement, check whether we come across a formula cell and retain a count of the number of formulas detected.

Top Articles
Latest Posts
Article information

Author: Pres. Lawanda Wiegand

Last Updated:

Views: 6212

Rating: 4 / 5 (51 voted)

Reviews: 82% of readers found this page helpful

Author information

Name: Pres. Lawanda Wiegand

Birthday: 1993-01-10

Address: Suite 391 6963 Ullrich Shore, Bellefort, WI 01350-7893

Phone: +6806610432415

Job: Dynamic Manufacturing Assistant

Hobby: amateur radio, Taekwondo, Wood carving, Parkour, Skateboarding, Running, Rafting

Introduction: My name is Pres. Lawanda Wiegand, I am a inquisitive, helpful, glamorous, cheerful, open, clever, innocent person who loves writing and wants to share my knowledge and understanding with you.