Working with Ranges

A Range object can represent a single cell, a range of cells, an entire row or column, or a selection containing multiple ranges.

Note that if a worksheet is not specified, VBA will assume that the cells are in the active sheet, which is fine if your code is attached to that specific sheet. If you’re working with multiple worksheets in the same module, remember to define all of your ranges specifying a worksheet.

Here are some of the more important methods that we use to work with ranges:

1. Setting range variables: use the Set statement to set range variables:

Dim myRange as Range
Set myRange = Range(“A1”)

You can then refer to the range by name, instead of by cell.

myRange.Value=”hello world”

2. Range method: returns a range object. The argument is a string that’s either an A1-style reference or the name of a range that was defined in Excel. To name a range in Excel, select the range, right click, and choose Define name.

snip

Worksheets(“Sheet1”).Range(“A1”).Value=3
Range(“A1:A3”).Value=4
Range(“range3”).Formula = “=5*RAND()”

3. Cells method: is similar to the Range method, but takes numeric arguments instead of string arguments. Note that the values are (row, column)–this might feel weird because it’s sort of like (y,x) instead of (x,y).

Worksheets(“Sheet1”).Cells(1,1).Value=3
Cells(1,1).Formula=”=10*RAND()”

You can combine the range and cells methods to return a region. The following statement selects cells A1:C4

Range(Cells(1,1), Cells(3,4)).select

3. Offset method: takes an input Range object, and RowOffset and ColumnOffset arguments, returning a new range. This is particularly handy in combination with the “with” programming structure: you can refer to multiple offset values in a compact way.

Range(“A1”).Offset(0,1).Value = 2
With Range(“A1:B5”)
.Offset(0,1).Value = 2
.Offset(0,2).Value = “hello”
End With

4. End property: returns the last non-empty cell in a column/row:

ActiveCell.End(xlDown)
Range(ActiveCell, ActiveCell.End(xlDown))

Other directions: xlUp, xlToLeft and xlToRight

5. CurrentRegion property: returns the range of cells bounded by empty rows and empty columns

Range(“A1”).CurrentRegion.select

6. UsedRange property: returns the rectangular range that contains every nonempty cell of the worksheet.

Set myRange=Worksheets(“Sheet1”).Range(“A1”).UsedRange

7. Union method: create a new range by referring to multiple other ranges.

Union(Range(“A1”).CurrentRegion, Range(“A21”)).select

 

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.