Range Object: Range Examples Cells Declare A Range Object Select Rows Columns Copy/Paste Clear Count
Range Object: Range Examples Cells Declare A Range Object Select Rows Columns Copy/Paste Clear Count
4. Range Object
Range Examples | Cells | Declare a Range Object | Select | Rows | Columns | Copy/Paste | Clear |
Count
The Range object, which is the representation of a cell (or cells) on your worksheet, is the most
important object of Excel VBA. This chapter gives an overview of the properties and methods of
the Range object. Properties are something which an object has (they describe the object),
while methods do something (they perform an action with an object).
Range Examples
Place a command button on your worksheet and add the following code line:
Range("B3").Value = 2
Code:
Range("A1:A4").Value = 5
Result:
Code:
Range("A1:A2,B3:C4").Value = 10
Result:
Note: to refer to a named range in your Excel VBA code, use a code line like this:
Range("Prices").Value = 15
Cells
Instead of Range, you can also use Cells. Using Cells is particularly useful when you want to loop through ranges.
Code:
Cells(3, 2).Value = 2
Result:
Explanation: Excel VBA enters the value 2 into the cell at the intersection of row 3 and column 2.
Code:
Result:
Code:
Dim example As Range
Set example = Range("A1:C4")
example.Value = 8
Result:
Select
An important method of the Range object is the Select method. The Select method simply selects a range.
Code:
example.Select
Result:
Note: to select cells on a different worksheet, you have to activate this sheet first. For example, the following code
lines select cell B7 on the third worksheet from the left.
Worksheets(3).Activate
Worksheets(3).Range("B7").Select
Rows
The Rows property gives access to a specific row of a range.
Code:
Result:
Columns
The Columns property gives access to a specific column of a range.
Code:
example.Columns(2).Select
Result:
Copy/Paste
The Copy and Paste method are used to copy a range and to paste it somewhere else on the worksheet.
Code:
Range("A1:A2").Select
Selection.Copy
Range("C3").Select
ActiveSheet.Paste
Result:
Although this is allowed in Excel VBA, it is much better to use the code line below which does exactly the same.
Range("C3:C4").Value = Range("A1:A2").Value
Clear
To clear the content of an Excel range, you can use the ClearContents method.
Range("A1").ClearContents
or simply use:
Range("A1").Value = ""
Note: use the Clear method to clear the content and format of a range. Use the ClearFormats method to clear the
format only.
Count
With the Count property, you can count the number of cells, rows and columns of a range.
Code:
MsgBox example.Count
Result:
Code:
MsgBox example.Rows.Count
Result:
Note: in a similar way, you can count the number of columns of a range.
4.1 CurrentRegion
This example illustrates the CurrentRegion property in Excel VBA. The current region is a range
bounded by any combination of blank rows and blank columns. Can you find the current region
of cell A1?
Place a command button on your worksheet and add the following code line:
Range("A1").CurrentRegion.Select
Result when you click the command button on the sheet:
Here is another example. Can you find the current region of cell B3?
Code:
Range("B3").CurrentRegion.Select
Result:
The value 1 in row 1 has no influence on the current region of cell B3. Row 2 is empty!
Below we will look at a program in Excel VBA that colors the maximum value of a dynamic
range.
Situation:
Each time we add a number and we click the command button, we want Excel VBA to color the
maximum value of these numbers.
Place a command button on your worksheet and add the following code lines:
1. First, we declare one variable and two Range objects. One variable of type Double we call maximum. We call the
Range objects rng and cell.
2. We add the line which changes the background color of all cells to 'No Fill'.
Cells.Interior.ColorIndex = 0
3. We initialize rng with the numbers. We use the CurrentRegion property for this. CurrentRegion is useful when we
don't know the exact boundaries of a range in advance.
Set rng = Range("A1").CurrentRegion
4. We initialize maximum with the maximum value of the numbers. We use the worksheet function Max to find the
maximum value.
maximum = WorksheetFunction.Max(rng)
5. Finally, we color the maximum value. We use a For Each Next Loop.
Note: instead of ColorIndex number 22 (red), you can use any ColorIndex number.
6. Add a number.
The Resize property in Excel VBA makes a range (border below for illustration only) a specific
number of rows and columns larger or smaller. The Resize property always takes the top left cell
of a range as the starting point.
Code line:
Range("A1:C4").Resize(3, 2).Select
Result:
Explanation: this code line resizes Range("A1:C4") to 3 rows and 2 columns and selects this range.
Code line:
Range("A1:C4").Resize(, 1).Select
Result:
Explanation: this code line resizes Range("A1:C4") to 1 column (we omit any row specification) and selects this
range.
This example teaches you how to select entire rows and columns in Excel VBA. Are you ready?
Place a command button on your worksheet and add the following code lines:
1. The following code line selects the entire sheet.
Cells.Select
Note: because we placed our command button on the first worksheet, this code line selects the entire
first sheet. To select cells on another worksheet, you have to activate this sheet first. For example, the
following code lines select the entire second worksheet.
Worksheets(2).Activate
Worksheets(2).Cells.Select
Columns(2).Select
3. The following code line selects the seventh row.
Rows(7).Select
Rows("5:7").Select
Columns("B:E").Select
6. Be careful not to mix up the Rows and Columns properties with the Row and Column properties. The Rows and
Columns properties return a Range object. The Row and Column properties return a single value.
Code line:
Result:
7. Select cell D6. The following code line selects the entire row of the active cell.
ActiveCell.EntireRow.Select
ActiveCell.EntireColumn.Cells(1).Value = 2
9. Select cell D6. The following code line enters the value 3 into the first cell of the row below the row that contains
the active cell.
ActiveCell.EntireRow.Offset(1, 0).Cells(1).Value = 3
5. Offset
The Offset property in Excel VBA takes the range which is a particular number of rows and
columns away from a certain range (border below for illustration only).
Place a command button on your worksheet and add the following code lines:
Dim example As Range
Set example = Range("A1:A2")
example.Offset(3, 2).Select
Result when you click the command button on the sheet:
Explanation: these code lines select the range which is 3 rows below and 2 columns to the right of Range("A1:A2").
The Offset property always takes the top left cell of a range as the starting point.
For a practical example of the offset property, see our example program Create a Pattern.
This example illustrates the End property of the Range object in Excel VBA. We will use this
property to select the range from the Active Cell to the last entry in a column.
Situation:
Some sales figures in column A. Assume that you will be adding more sales figures over time.
Place a command button on your worksheet and add the following code lines:
1. To select the last entry in a column, simply add the following code line:
Range("A5").End(xlDown).Select
Note: instead of Range("A5"), you can also use Range("A1"), Range("A2"), etc. This code line is equivalent to
pressing the END+DOWN ARROW.
2. To select the range from cell A5 to the last entry in the column, add the following code line:
Range(Range("A5"), Range("A5").End(xlDown)).Select
3. To select the range from the Active Cell to the last entry in the column, simply replace Range("A5") with ActiveCell.
Range(ActiveCell, ActiveCell.End(xlDown)).Select
Result when you select cell A2 and click the command button on the sheet:
Note: you can use the constants xlUp, xlToRight and xlToLeft to move in the other directions. This way you can select
a range from the Active Cell to the last entry in a row.
Result:
Note: the Union method doesn't return the mathematical union (cell C6 and cell C7 are included twice).
The Intersect method in Excel VBA returns a Range object that represents the intersection of two or more ranges
(borders below for illustration only).
Code line:
Intersect(Range("B2:C7"), Range("C6:F8")).Select
Result:
This program in Excel VBA uses the Count property, IsNumeric function, IsEmpty function and
Intersect method to test a selection.
Situation:
Place a command button on your worksheet and add the following code lines:
1. First, we declare two Range objects. We call the Range objects rng and cell.
Explanation: Intersect(rng, cell) returns a Range object that represents the intersection of the two ranges. If this range
object is not Nothing, the single number (first three conditions) is in the bordered range.
4. Test the program.
Only when you select a single number in the bordered range the result will be:
Below we will look at a program in Excel VBA that shows a print preview of all the possible
football matches from a list of teams.
Situation:
1. First, we declare one Range object and four variables. We call the Range object rng. One String variable we call
matchname, and three Integer variables we call counter, i and j.
2. We initialize rng with the team names. We use CurrentRegion because we don't know the exact boundaries of the
range in advance (we want this program to work for 3 teams but also for 12 teams). We initialize counter with value 0.
Set rng = Range("A1").CurrentRegion
counter = 0
3. We write all the possible football matches to column C. First, we empty column C.
Worksheets(1).Columns(3) = ""
For example, for i = 1 and j = 2, Excel VBA writes the matchname Kickers vs Shooters. For i = 1 and j = 3, Excel VBA
writes the matchname Kickers vs Little Giants, etc.
7. The counter keeps track of the number of matchnames written to column C. Excel VBA increments counter by 1
each time it writes a matchname to column C. To achieve this, add the following code line:
counter = counter + 1
Next j
Next i
ActiveSheet.Columns(3).PrintPreview
4.10 Font
The Font property of the Range object in Excel VBA gives access to a lot of other properties.
That is because the Font property returns an object itself; the Font object. The Font object has
many properties like the Color property and the Bold property.
Color property
To change the color of an Excel range, use the Font property of the Range object, and then the
Color property of the Font object.
1. Add the following code line:
Range("A1").Font.Color = -16776961
Explanation: Where do we get this strange number from? Well, we started the Macro
Recorder and changed the color of a cell to red. You can to this for every color!
Range("A1").Font.Color = vbRed
Explanation: vbRed is a sort of built-in constant in Excel VBA. Place your cursor on vbRed in the Visual Basic Editor
and click F1 to see which other constants you can use.
Range("A1").Font.Color = RGB(255, 0, 0)
Explanation: RGB stands for Red, Green and Blue. These are the three primary colors. Each component can take on
a value from 0 to 255. With this function you can make every color. RGB(255,0,0) gives the pure Red color.
Bold property
The following code line bolds a range:
Range("A1").Font.Bold = True
To unbold a range, you can use the False keyword. The Font object has many more properties. If you want to
program these sort of things, just use the Macro Recorder to see how to do it! Usually code created by the Macro
Recorder is too long. For example, the Macro Recorder creates the following code when we bold Range("A1").
We have just seen that these two code lines can be written as one code line.
4.11 Background Colors
Changing background colors in Excel VBA is easy. Use the Interior property to return an Interior
object. Then use the ColorIndex property of the Interior object to set the background color of a
cell.
Place three command buttons on your worksheet and add the following code lines:
1. The code line below sets the background color of cell A1 to light blue.
Range("A1").Interior.ColorIndex = 37
Result:
2. The following code line sets the background color of cell A1 to 'No Fill'.
Range("A1").Interior.ColorIndex = 0
Result:
3. If you want to know the ColorIndex number of a color, simply ask Excel VBA.
MsgBox Selection.Interior.ColorIndex
4. The ColorIndex property gives access to 56 "preset" colors. If you can't find the specific color you are looking for,
use the Color property and the RGB function.
Range("A1").Interior.Color = RGB(255, 0, 0)
Explanation: RGB stands for Red, Green and Blue. These are the three primary colors. Each component can take on
a value from 0 to 255. With this function you can make every color. RGB(255,0,0) gives the pure Red color (exact
same result as above).
4.12 Areas Collection
This example illustrates the Areas collection in Excel VBA. Below we have bordered
Range("B2:C3,C5:E5"). This range has two areas. The comma separates the two areas.
Place a command button on your worksheet and add the following code lines:
1. First, we declare two Range objects. We call the Range objects rangeToUse and singleArea.
3. To count the number of areas of rangeToUse, add the following code line:
MsgBox rangeToUse.Areas.Count
Result:
4. You can refer to the different areas of rangeToUse by using the index values. The following code line counts the
numbers of cells of the first area.
MsgBox rangeToUse.Areas(1).Count
Result:
5. You can also loop through each area of rangeToUse and count the number of cells of each area. The macro below
does the trick.
Result:
For a practical example of the areas collection, see our example program Compare Ranges.
Below we will look at a program in Excel VBA that compares randomly selected ranges and
highlights cells that are unique. If you are not familiar with areas yet, we highly recommend you
to read this example first.
Situation:
Note: the only unique value in this example is the 3 since all other values occur in at least one more area. To select
Range("B2:B7,D3:E6,D8:E9"), hold down Ctrl and select each area.
Place a command button on your worksheet and add the following code lines:
1. First, we declare four Range objects and two variables of type Integer.
3. Add the line which changes the background color of all cells to 'No Fill'. Also add the line which removes the
borders of all cells.
Cells.Interior.ColorIndex = 0
Cells.Borders.LineStyle = xlNone
End If
The next code lines (at 5, 6 and 7) must be added between Else and End If.
rangeToUse.Interior.ColorIndex = 38
For i = 1 To rangeToUse.Areas.Count
For j = i + 1 To rangeToUse.Areas.Count
For Each cell1 In rangeToUse.Areas(i)
For Each cell2 In rangeToUse.Areas(j)
If cell1.Value = cell2.Value Then
cell1.Interior.ColorIndex = 0
cell2.Interior.ColorIndex = 0
End If
Next cell2
Next cell1
Next j
Next i
Explanation: this may look a bit overwhelming, but it's not that difficult. rangeToUse.Areas.Count equals 3, so the first
two code lines reduce to For i = 1 to 3 and For j = i + 1 to 3. For i = 1, j = 2, Excel VBA compares all values of the first
area with all values of the second area. For i = 1, j = 3, Excel VBA compares all values of the first area with all values
of the third area. For i = 2, j = 3, Excel VBA compares all values of the second area with all values of the third area. If
values are the same, it sets the background color of both cells to 'No Fill', because they are not unique.