Select one row in excel vba


VBA Select

It is very common to find the .Select methods in saved macro recorder code, next to a Range object.

.Select is used to select one or more elements of Excel (as can be done by using the mouse) allowing further manipulation of them.

Selecting cells with the mouse:

Select with the Mouse

Selecting cells with VBA:

    'Range([cell1],[cell2])
    Range(Cells(1, 1), Cells(9, 5)).Select
    Range("A1", "E9").Select
    Range("A1:E9").Select

Each of the above lines select the range from «A1» to «E9».

Select with VBA


VBA Select CurrentRegion

If a region is populated by data with no empty cells, an option for an automatic selection is the CurrentRegion property alongside the .Select method.

CurrentRegion.Select will select, starting from a Range, all the area populated with data.

    Range("A1").CurrentRegion.Select

CurrentRegion

Make sure there are no gaps between values, as CurrentRegion will map the region through adjoining cells (horizontal, vertical and diagonal).

  Range("A1").CurrentRegion.Select

With all the adjacent data

CurrentRegion Data

Not all adjacent data

CurrentRegion Missing Data

«C4» is not selected because it is not immediately adjacent to any filled cells.


VBA ActiveCell

The ActiveCell property brings up the active cell of the worksheet.

In the case of a selection, it is the only cell that stays white.

A worksheet has only one active cell.

    Range("B2:C4").Select
    ActiveCell.Value = "Active"

ActiveCell

Usually the ActiveCell property is assigned to the first cell (top left) of a Range, although it can be different when the selection is made manually by the user (without macros).

ActiveCell Under

The AtiveCell property can be used with other commands, such as Resize.


VBA Selection

After selecting the desired cells, we can use Selection to refer to it and thus make changes:

    Range("A1:D7").Select
    Selection = 7

Example Selection

Selection also accepts methods and properties (which vary according to what was selected).

    Selection.ClearContents 'Deletes only the contents of the selection
    Selection.Interior.Color = RGB(255, 255, 0) 'Adds background color to the selection

Clear Selection

As in this case a cell range has been selected, the Selection will behave similarly to a Range. Therefore, Selection should also accept the .Interior.Color property.

RGB (Red Green Blue) is a color system used in a number of applications and languages. The input values for each color, in the example case, ranges from 0 to 255.


Selection FillDown

If there is a need to replicate a formula to an entire selection, you can use the .FillDown method

    Selection.FillDown

Before the FillDown

Before Filldown

After the FillDown

After FillDown

.FillDown is a method applicable to Range. Since the Selection was done in a range of cells (equivalent to a Range), the method will be accepted.

.FillDown replicates the Range/Selection formula of the first line, regardless of which ActiveCell is selected.

.FillDown can be used at intervals greater than one column (E.g. Range(«B1:C2»).FillDown will replicate the formulas of B1 and C1 to B2 and C2 respectively).


VBA EntireRow and EntireColumn

You can select one or multiple rows or columns with VBA.

    Range("B2").EntireRow.Select
    Range("C3:D3").EntireColumn.Select

Select EntireColumn

The selection will always refer to the last command executed with Select.

To insert a row use the Insert method.

    Range("A7").EntireRow.Insert
    'In this case, the content of the seventh row will be shifted downward

To delete a row use the Delete method.

    Range("A7").EntireRow.Delete
    'In this case, the content of the eighth row will be moved to the seventh

VBA Rows and Columns

Just like with the EntireRow and EntireColumn property, you can use Rows and Columns to select a row or column.

    Columns(5).Select
    Rows(3).Select

Select Rows

To hide rows:

    Range("A1:C3").Rows.Hidden = True

Hidden Cells

In the above example, rows 1 to 3 of the worksheet were hidden.


VBA Row and Column

Row and Column are properties that are often used to obtain the numerical address of the first row or first column of a selection or a specific cell.

    Range("A3:H30").Row 'Referring to the row; returns 3
    Range("B3").Column  'Referring to the column; returns 2

The results of Row and Column are often used in loops or resizing.



Consolidating Your Learning

Suggested Exercise



SuperExcelVBA.com is learning website. Examples might be simplified to improve reading and basic understanding. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. All Rights Reserved.

Excel ® is a registered trademark of the Microsoft Corporation.

© 2023 SuperExcelVBA | ABOUT

Protected by Copyscape

In this Article

  • Select Entire Rows or Columns
    • Select Single Row
    • Select Single Column
    • Select Multiple Rows or Columns
    • Select ActiveCell Row or Column
    • Select Rows and Columns on Other Worksheets
    • Is Selecting Rows and Columns Necessary?
  • Methods and Properties of Rows & Columns
    • Delete Entire Rows or Columns
    • Insert Rows or Columns
    • Copy & Paste Entire Rows or Columns
    • Hide / Unhide Rows and Columns
    • Group / UnGroup Rows and Columns
    • Set Row Height or Column Width
    • Autofit Row Height / Column Width
  • Rows and Columns on Other Worksheets or Workbooks
  • Get Active Row or Column

This tutorial will demonstrate how to select and work with entire rows or columns in VBA.

First we will cover how to select entire rows and columns, then we will demonstrate how to manipulate rows and columns.

Select Entire Rows or Columns

Select Single Row

You can select an entire row with the Rows Object like this:

Rows(5).Select

Or you can use EntireRow along with the Range or Cells Objects:

Range("B5").EntireRow.Select

or

Cells(5,1).EntireRow.Select

You can also use the Range Object to refer specifically to a Row:

Range("5:5").Select

Select Single Column

Instead of the Rows Object, use the Columns Object to select columns. Here you can reference the column number 3:

Columns(3).Select

or letter “C”, surrounded by quotations:

Columns("C").Select

Instead of EntireRow, use EntireColumn along with the Range or Cells Objects to select entire columns:

Range("C5").EntireColumn.Select

or

Cells(5,3).EntireColumn.Select

You can also use the Range Object to refer specifically to a column:

Range("B:B").Select

Select Multiple Rows or Columns

Selecting multiple rows or columns works exactly the same when using EntireRow or EntireColumn:

Range("B5:D10").EntireRow.Select

or

Range("B5:B10").EntireColumn.Select

However, when you use the Rows or Columns Objects, you must enter the row numbers or column letters in quotations:

Rows("1:3").Select

or

Columns("B:C").Select

Select ActiveCell Row or Column

To select the ActiveCell Row or Column, you can use one of these lines of code:

ActiveCell.EntireRow.Select

or

ActiveCell.EntireColumn.Select

Select Rows and Columns on Other Worksheets

In order to select Rows or Columns on other worksheets, you must first select the worksheet.

Sheets("Sheet2").Select
Rows(3).Select

The same goes for when selecting rows or columns in other workbooks.

Workbooks("Book6.xlsm").Activate
Sheets("Sheet2").Select
Rows(3).Select

Note: You must Activate the desired workbook. Unlike the Sheets Object, the Workbook Object does not have a Select Method.

VBA Coding Made Easy

Stop searching for VBA code online. Learn more about AutoMacro — A VBA Code Builder that allows beginners to code procedures from scratch with minimal coding knowledge and with many time-saving features for all users!

automacro

Learn More

Is Selecting Rows and Columns Necessary?

However, it’s (almost?) never necessary to actually select Rows or Columns. You don’t need to select a Row or Column in order to interact with them. Instead, you can apply Methods or Properties directly to the Rows or Columns. The next several sections will demonstrate different Methods and Properties that can be applied.

You can use any method listed above to refer to Rows or Columns.

Methods and Properties of Rows & Columns

Delete Entire Rows or Columns

To delete rows or columns, use the Delete Method:

Rows("1:4").Delete

or:

Columns("A:D").Delete

VBA Programming | Code Generator does work for you!

Insert Rows or Columns

Use the Insert Method to insert rows or columns:

Rows("1:4").Insert

or:

Columns("A:D").Insert

Copy & Paste Entire Rows or Columns

Paste Into Existing Row or Column

When copying and pasting entire rows or columns you need to decide if you want to paste over an existing row / column or if you want to insert a new row / column to paste your data.

These first examples will copy and paste over an existing row or column:

Range("1:1").Copy Range("5:5")

or

Range("C:C").Copy Range("E:E")

Insert & Paste

These next examples will paste into a newly inserted row or column.

This will copy row 1 and insert it into row 5, shifting the existing rows down:

Range("1:1").Copy
Range("5:5").Insert

This will copy column C and insert it into column E, shifting the existing columns to the right:

Range("C:C").Copy
Range("E:E").Insert

Hide / Unhide Rows and Columns

To hide rows or columns set their Hidden Properties to True. Use False to hide the rows or columns:

'Hide Rows
Rows("2:3").EntireRow.Hidden = True

'Unhide Rows
Rows("2:3").EntireRow.Hidden = False

or

'Hide Columns
Columns("B:C").EntireColumn.Hidden = True

'Unhide Columns
Columns("B:C").EntireColumn.Hidden = False

Group / UnGroup Rows and Columns

If you want to Group rows (or columns) use code like this:

'Group Rows
Rows("3:5").Group

'Group Columns
Columns("C:D").Group

To remove the grouping use this code:

'Ungroup Rows
Rows("3:5").Ungroup

'Ungroup Columns
Columns("C:D").Ungroup

This will expand all “grouped” outline levels:

ActiveSheet.Outline.ShowLevels RowLevels:=8, ColumnLevels:=8

and this will collapse all outline levels:

ActiveSheet.Outline.ShowLevels RowLevels:=1, ColumnLevels:=1

Set Row Height or Column Width

To set the column width use this line of code:

Columns("A:E").ColumnWidth = 30

To set the row height use this line of code:

Rows("1:1").RowHeight = 30

AutoMacro | Ultimate VBA Add-in | Click for Free Trial!

Autofit Row Height / Column Width

To Autofit a column:

Columns("A:B").Autofit

To Autofit a row:

Rows("1:2").Autofit

Rows and Columns on Other Worksheets or Workbooks

To interact with rows and columns on other worksheets, you must define the Sheets Object:

Sheets("Sheet2").Rows(3).Insert

Similarly, to interact with rows and columns in other workbooks, you must also define the Workbook Object:

Workbooks("book1.xlsm").Sheets("Sheet2").Rows(3).Insert

Get Active Row or Column

To get the active row or column, you can use the Row and Column Properties of the ActiveCell Object.

MsgBox ActiveCell.Row

or

MsgBox ActiveCell.Column

This also works with the Range Object:

MsgBox Range("B3").Column

How can I select the row associated with the current active cell AND the first row?

I have:

    Rows(ActiveCell.Row).Select
    Range("1:1").Select

But when the second «Select» is run, it removes the first select, so I end with just the first row. How to I get both selected at once?

Thank you!

luchaninov's user avatar

luchaninov

6,7046 gold badges58 silver badges75 bronze badges

asked Jun 24, 2013 at 21:16

halcyon27's user avatar

1

 Union(ActiveCell.EntireRow, Cells(1, 1).EntireRow).Select

answered Jun 24, 2013 at 21:23

mr.Reband's user avatar

mr.Rebandmr.Reband

2,4362 gold badges17 silver badges22 bronze badges

0

The VBA Range Object

The Excel Range Object is an object in Excel VBA that represents a cell, row, column, a selection of cells or a 3 dimensional range. The Excel Range is also a Worksheet property that returns a subset of its cells.

Worksheet Range

The Range is a Worksheet property which allows you to select any subset of cells, rows, columns etc.

Dim r as Range 'Declared Range variable

Set r = Range("A1") 'Range of A1 cell

Set r = Range("A1:B2") 'Square Range of 4 cells - A1,A2,B1,B2

Set r= Range(Range("A1"), Range ("B1")) 'Range of 2 cells A1 and B1

Range("A1:B2").Select 'Select the Cells A1:B2 in your Excel Worksheet

Range("A1:B2").Activate 'Activate the cells and show them on your screen (will switch to Worksheet and/or scroll to this range.

Select a cell or Range of cells using the Select method. It will be visibly marked in Excel:
range select cell

Working with Range variables

The Range is a separate object variable and can be declared as other variables. As the VBA Range is an object you need to use the Set statement:

Dim myRange as Range 
'...
Set myRange = Range("A1") 'Need to use Set to define myRange

The Range object defaults to your ActiveWorksheet. So beware as depending on your ActiveWorksheet the Range object will return values local to your worksheet:

Range("A1").Select
'...is the same as...
ActiveSheet.Range("A1").Select

You might want to define the Worksheet reference by Range if you want your reference values from a specifc Worksheet:

Sheets("Sheet1").Range("A1").Select 'Will always select items from Worksheet named Sheet1

The ActiveWorkbook is not same to ThisWorkbook. Same goes for the ActiveSheet. This may reference a Worksheet from within a Workbook external to the Workbook in which the macro is executed as Active references simply the currently top-most worksheet. Read more here

Range properties

The Range object contains a variety of properties with the main one being it’s Value and an the second one being its Formula.

A Range Value is the evaluated property of a cell or a range of cells. For example a cell with the formula =10+20 has an evaluated value of 20.
A Range Formula is the formula provided in the cell or range of cells. For example a cell with a formula of =10+20 will have the same Formula property.

'Let us assume A1 contains the formula "=10+20"

Debug.Print Range("A1").Value 'Returns: 30

Debug.Print Range("A1").Formula 'Returns: =10+20

Other Range properties include:
Work in progress

Worksheet Cells

A Worksheet Cells property is similar to the Range property but allows you to obtain only a SINGLE CELL, based on its row and column index. Numbering starts at 1:
cells select cell

The Cells property is in fact a Range object not a separate data type.
Excel facilitates a Cells function that allows you to obtain a cell from within the ActiveSheet, current top-most worksheet.

Cells(2,2).Select 'Selects B2
'...is the same as...
ActiveSheet.Cells(2,2).Select 'Select B2

Cells are Ranges which means they are not a separate data type:

Dim myRange as Range
Set myRange = Cells(1,1) 'Cell A1

Range Rows and Columns

As we all know an Excel Worksheet is divided into Rows and Columns. The Excel VBA Range object allows you to select single or multiple rows as well as single or multiple columns. There are a couple of ways to obtain Worksheet rows in VBA:

Getting an entire row or column

entirerow rangeTo get and entire row of a specified Range you need to use the EntireRow property. Although, the function’s parameters suggest taking both a RowIndex and ColumnIndex it is enough just to provide the row number. Row indexing starts at 1.
entirecolumn rangeTo get and entire column of a specified Range you need to use the EntireColumn property. Although, the function’s parameters suggest taking both a RowIndex and ColumnIndex it is enough just to provide the column number. Column indexing starts at 1.

Range("B2").EntireRows(1).Hidden = True 'Gets and hides the entire row 2

Range("B2").EntireColumns(1).Hidden = True 'Gets and hides the entire column 2

The three properties EntireRow/EntireColumn, Rows/Columns and Row/Column are often misunderstood so read through to understand the differences.

Get a row/column of a specified range

range rows functionIf you want to get a certain row within a Range simply use the Rows property of the Worksheet. Although, the function’s parameters suggest taking both a RowIndex and ColumnIndex it is enough just to provide the row number. Row indexing starts at 1.
range columns functionSimilarly you can use the Columns function to obtain any single column within a Range. Although, the function’s parameters suggest taking both a RowIndex and ColumnIndex actually the first argument you provide will be the column index. Column indexing starts at 1.

Rows(1).Hidden = True 'Hides the first row in the ActiveSheet
'same as
ActiveSheet.Rows(1).Hidden = True

Columns(1).Hidden = True 'Hides the first column in the ActiveSheet
'same as
ActiveSheet.Columns(1).Hidden = True

To get a range of rows/columns you need to use the Range function like so:

Range(Rows(1), Rows(3)).Hidden = True 'Hides rows 1:3
'same as
Range("1:3").Hidden = True
'same as 
ActiveSheet.Range("1:3").Hidden = True

Range(Columns(1), Columns(3)).Hidden = True 'Hides columns A:C
'same as
Range("A:C").Hidden = True
'same as 
ActiveSheet.Range("A:C").Hidden = True

Get row/column of specified range

The above approach assumed you want to obtain only rows/columns from the ActiveSheet – the visible and top-most Worksheet. Usually however, you will want to obtain rows or columns of an existing Range. Similarly as with the Worksheet Range property, any Range facilitates the Rows and Columns property.

Dim myRange as Range
Set myRange = Range("A1:C3")

myRange.Rows.Hidden = True 'Hides rows 1:3
myRange.Columns.Hidden = True 'Hides columns A:C

Set myRange = Range("C10:F20")
myRange.Rows(2).Hidden = True 'Hides rows 11
myRange.Columns(3).Hidden = True 'Hides columns E

Getting a Ranges first row/column number

Aside from the Rows and Columns properties Ranges also facilitate a Row and Column property which provide you with the number of the Ranges first row and column.

Set myRange = Range("C10:F20")

'Get first row number
Debug.Print myRange.Row 'Result: 10
'Get first column number
Debug.Print myRange.Column 'Result: 3

Converting Column number to Excel Column

This is an often question that turns up – how to convert a column number to a string e.g. 100 to “CV”.

Function GetExcelColumn(columnNumber As Long)
    Dim div As Long, colName As String, modulo As Long
    div = columnNumber: colName = vbNullString

    Do While div > 0
        modulo = (div - 1) Mod 26
        colName = Chr(65 + modulo) & colName
        div = ((div - modulo) / 26)
    Loop

    GetExcelColumn = colName
End Function

Range Cut/Copy/Paste

Cutting and pasting rows is generally a bad practice which I heavily discourage as this is a practice that is moments can be heavily cpu-intensive and often is unaccounted for.

Copy function

Range copy functionThe Copy function works on a single cell, subset of cell or subset of rows/columns.

'Copy values and formatting from cell A1 to cell D1
Range("A1").Copy Range("D1")

'Copy 3x3 A1:C3 matrix to D1:F3 matrix - dimension must be same
Range("A1:C3").Copy Range("D1:F3")

'Copy rows 1:3 to rows 4:6
Range("A1:A3").EntireRow.Copy Range("A4")

'Copy columns A:C to columns D:F
Range("A1:C1").EntireColumn.Copy Range("D1")

The Copy function can also be executed without an argument. It then copies the Range to the Windows Clipboard for later Pasting.

Cut function

range cut functionThe Cut function, similarly as the Copy function, cuts single cells, ranges of cells or rows/columns.

'Cut A1 cell and paste it to D1
Range("A1").Cut Range("D1")

'Cut 3x3 A1:C3 matrix and paste it in D1:F3 matrix - dimension must be same
Range("A1:C3").Cut Range("D1:F3")

'Cut rows 1:3 and paste to rows 4:6
Range("A1:A3").EntireRow.Cut Range("A4")

'Cut columns A:C and paste to columns D:F
Range("A1:C1").EntireColumn.Cut Range("D1")

The Cut function can be executed without arguments. It will then cut the contents of the Range and copy it to the Windows Clipboard for pasting.

Cutting cells/rows/columns does not shift any remaining cells/rows/columns but simply leaves the cut out cells empty

PasteSpecial function

range pastespecial functionThe Range PasteSpecial function works only when preceded with either the Copy or Cut Range functions. It pastes the Range (or other data) within the Clipboard to the Range on which it was executed.

Syntax

The PasteSpecial function has the following syntax:

PasteSpecial( Paste, Operation, SkipBlanks, Transpose)

The PasteSpecial function can only be used in tandem with the Copy function (not Cut)

Parameters

Paste
The part of the Range which is to be pasted. This parameter can have the following values:

Parameter Constant Description
xlPasteSpecialOperationAdd 2 Copied data will be added with the value in the destination cell.
xlPasteSpecialOperationDivide 5 Copied data will be divided with the value in the destination cell.
xlPasteSpecialOperationMultiply 4 Copied data will be multiplied with the value in the destination cell.
xlPasteSpecialOperationNone -4142 No calculation will be done in the paste operation.
xlPasteSpecialOperationSubtract 3 Copied data will be subtracted with the value in the destination cell.

Operation
The paste operation e.g. paste all, only formatting, only values, etc. This can have one of the following values:

Name Constant Description
xlPasteAll -4104 Everything will be pasted.
xlPasteAllExceptBorders 7 Everything except borders will be pasted.
xlPasteAllMergingConditionalFormats 14 Everything will be pasted and conditional formats will be merged.
xlPasteAllUsingSourceTheme 13 Everything will be pasted using the source theme.
xlPasteColumnWidths 8 Copied column width is pasted.
xlPasteComments -4144 Comments are pasted.
xlPasteFormats -4122 Copied source format is pasted.
xlPasteFormulas -4123 Formulas are pasted.
xlPasteFormulasAndNumberFormats 11 Formulas and Number formats are pasted.
xlPasteValidation 6 Validations are pasted.
xlPasteValues -4163 Values are pasted.
xlPasteValuesAndNumberFormats 12 Values and Number formats are pasted.

SkipBlanks
If True then blanks will not be pasted.

Transpose
Transpose the Range before paste (swap rows with columns).

PasteSpecial Examples

'Cut A1 cell and paste its values to D1
Range("A1").Copy
Range("D1").PasteSpecial
 
'Copy 3x3 A1:C3 matrix and add all the values to E1:G3 matrix (dimension must be same)
Range("A1:C3").Copy 
Range("E1:G3").PasteSpecial xlPasteValues, xlPasteSpecialOperationAdd

Below an example where the Excel Range A1:C3 values are copied an added to the E1:G3 Range. You can also multiply, divide and run other similar operations.
PasteSpecial example - Copy and Add

Paste

The Paste function allows you to paste data in the Clipboard to the actively selected Range. Cutting and Pasting can only be accomplished with the Paste function.

'Cut A1 cell and paste its values to D1
Range("A1").Cut
Range("D1").Select
ActiveSheet.Paste
 
'Cut 3x3 A1:C3 matrix and paste it in D1:F3 matrix - dimension must be same
Range("A1:C3").Cut 
Range("D1:F3").Select
ActiveSheet.Paste
 
'Cut rows 1:3 and paste to rows 4:6
Range("A1:A3").EntireRow.Cut 
Range("A4").Select
ActiveSheet.Paste
 
'Cut columns A:C and paste to columns D:F
Range("A1:C1").EntireColumn.Cut 
Range("D1").Select
ActiveSheet.Paste

Range Clear/Delete

The Clear function

The Clear function clears the entire content and formatting from an Excel Range. It does not, however, shift (delete) the cleared cells.

Range("A1:C3").Clear

Excel Range Clear function example

The Delete function

Range Delete functionThe Delete function deletes a Range of cells, removing them entirely from the Worksheet, and shifts the remaining Cells in a selected shift direction.
Although the manual Delete cell function provides 4 ways of shifting cells. The VBA Delete Shift values can only be either be xlShiftToLeft or xlShiftUp.

'If Shift omitted, Excel decides - shift up in this case
Range("B2").Delete 

'Delete and Shift remaining cells left
Range("B2").Delete xlShiftToLeft  

'Delete and Shift remaining cells up
Range("B2").Delete xlShiftTop

'Delete entire row 2 and shift up
Range("B2").EntireRow.Delete

'Delete entire column B and shift left
Range("B2").EntireRow.Delete

Excel Range Delete - shifting cells

Traversing Ranges

Traversing cells is really useful when you want to run an operation on each cell within an Excel Range. Fortunately this is easily achieved in VBA using the For Each or For loops.

Dim cellRange As Range
    
For Each cellRange In Range("A1:C3")
  Debug.Print cellRange.Value
Next cellRange

Although this may not be obvious, beware of iterating/traversing the Excel Range using a simple For loop. For loops are not efficient on Ranges. Use a For Each loop as shown above. This is because Ranges resemble more Collections than Arrays. Read more on For vs For Each loops here

Traversing the UsedRange

Excel Range - Worksheet UsedRangeEvery Worksheet has a UsedRange. This represents that smallest rectangle Range that contains all cells that have or had at some point values. In other words if the further out in the bottom, right-corner of the Worksheet there is a certain cell (e.g. E8) then the UsedRange will be as large as to include that cell starting at cell A1 (e.g. A1:E8). In Excel you can check the current UsedRange hitting CTRL+END. In VBA you get the UsedRange like this:

ActiveSheet.UsedRange
'same as
UsedRange

You can traverse through the UsedRange like this:

Dim cellRange As Range
    
For Each cellRange In UsedRange
  Debug.Print "Row: " & cellRange.Row & ", Column: " & cellRange.Column
Next cellRange

The UsedRange is a useful construct responsible often for bloated Excel Workbooks. Often delete unused Rows and Columns that are considered to be within the UsedRange can result in significantly reducing your file size. Read also more on the XSLB file format here

Range Addresses

The Excel Range Address property provides a string value representing the Address of the Range.
Excel Range Address property

Syntax

Below the syntax of the Excel Range Address property:

Address( [RowAbsolute], [ColumnAbsolute], [ReferenceStyle], [External], [RelativeTo] )

Parameters

RowAbsolute
Optional. If True returns the row part of the reference address as an absolute reference. By default this is True.

$D$10:$G$100 'RowAbsolute is set to True
$D10:$G100 'RowAbsolute is set to False

ColumnAbsolute
Optional. If True returns the column part of the reference as an absolute reference. By default this is True.

$D$10:$G$100 'ColumnAbsolute is set to True
D$10:G$100 'ColumnAbsolute is set to False

ReferenceStyle
Optional. The reference style. The default value is xlA1. Possible values:

Constant Value Description
xlA1 1 Default. Use xlA1 to return an A1-style reference
xlR1C1 -4150 Use xlR1C1 to return an R1C1-style reference

External
Optional. If True then property will return an external reference address, otherwise a local reference address will be returned. By default this is False.

$A$1 'Local
[Book1.xlsb]Sheet1!$A$1 'External

RelativeTo
Provided RowAbsolute and ColumnAbsolute are set to False, and the ReferenceStyle is set to xlR1C1, then you must include a starting point for the relative reference. This must be a Range variable to be set as the reference point.

Merged Ranges

Excel Range Merge functionMerged cells are Ranges that consist of 2 or more adjacent cells. To Merge a collection of adjacent cells run Merge function on that Range.

The Merge has only a single parameter – Across, a boolean which if True will merge cells in each row of the specified range as separate merged cells. Otherwise the whole Range will be merged. The default value is False.

Merge examples

To merge the entire Range:

'This will turn of any alerts warning that values may be lost
Application.DisplayAlerts = False

Range("B2:C3").Merge

This will result in the following:
Excel Range Merged cells
To merge just the rows set Across to True.

'This will turn of any alerts warning that values may be lost
Application.DisplayAlerts = False

Range("B2:C3").Merge True

This will result in the following:
Excel Range Merged cells across rows

Remember that merged Ranges can only have a single value and formula. Hence, if you merge a group of cells with more than a single value/formula only the first value/formula will be set as the value/formula for your new merged Range

Checking if Range is merged

To check if a certain Range is merged simply use the Excel Range MergeCells property:

Range("B2:C3").Merge

Debug.Print Range("B2").MergeCells 'Result: True

The MergeArea

The MergeArea is a property of an Excel Range that represent the whole merge Range associated with the current Range. Say that $B$2:$C$3 is a merged Range – each cell within that Range (e.g. B2, C3..) will have the exact same MergedArea. See example below:

Range("B2:C3").Merge
Debug.Print Range("B2").MergeArea.Address 'Result: $B$2:$C$3

Named Ranges

Named Ranges are Ranges associated with a certain Name (string). In Excel you can find all your Named Ranges by going to Formulas->Name Manager. They are very useful when working on certain values that are used frequently through out your Workbook. Imagine that you are writing a Financial Analysis and want to use a common Discount Rate across all formulas. Just the address of the cell e.g. “A2”, won’t be self-explanatory. Why not use e.g. “DiscountRate” instead? Well you can do just that.

Creating a Named Range

Named Ranges can be created either within the scope of a Workbook or Worksheet:

Dim r as Range
'Within Workbook
Set r = ActiveWorkbook.Names.Add("NewName", Range("A1"))
'Within Worksheet
Set r = ActiveSheet.Names.Add("NewName", Range("A1"))

This gives you flexibility to use similar names across multiple Worksheets or use a single global name across the entire Workbook.

Listing all Named Ranges

You can list all Named Ranges using the Name Excel data type. Names are objects that represent a single NamedRange. See an example below of listing our two newly created NamedRanges:

Call ActiveWorkbook.Names.Add("NewName", Range("A1"))
Call ActiveSheet.Names.Add("NewName", Range("A1"))

Dim n As Name
For Each n In ActiveWorkbook.Names
  Debug.Print "Name: " & n.Name & ", Address: " & _
       n.RefersToRange.Address & ", Value: "; n.RefersToRange.Value
Next n

'Result:
'Name: Sheet1!NewName, Address: $A$1, Value:  1 
'Name: NewName, Address: $A$1, Value:  1 

SpecialCells

SpecialCells are a very useful Excel Range property, that allows you to select a subset of cells/Ranges within a certain Range.

Syntax

The SpecialCells property has the following syntax:

SpecialCells( Type, [Value] )

Parameters

Type
The type of cells to be returned. Possible values:

Constant Value Description
xlCellTypeAllFormatConditions -4172 Cells of any format
xlCellTypeAllValidation -4174 Cells having validation criteria
xlCellTypeBlanks 4 Empty cells
xlCellTypeComments -4144 Cells containing notes
xlCellTypeConstants 2 Cells containing constants
xlCellTypeFormulas -4123 Cells containing formulas
xlCellTypeLastCell 11 The last cell in the used range
xlCellTypeSameFormatConditions -4173 Cells having the same format
xlCellTypeSameValidation -4175 Cells having the same validation criteria
xlCellTypeVisible 12 All visible cells

Value
If Type is equal to xlCellTypeConstants or xlCellTypeFormulas this determines the types of cells to return e.g. with errors.

Constant Value
xlErrors 16
xlLogical 4
xlNumbers 1
xlTextValues 2

SpecialCells examples

Get Excel Range with Constants

This will return only cells with constant cells within the Range C1:C3:

For Each r In Range("A1:C3").SpecialCells(xlCellTypeConstants)
  Debug.Print r.Value
Next r

Search for Excel Range with Errors

For Each r In ActiveSheet.UsedRange.SpecialCells(xlCellTypeFormulas, xlErrors)
  Debug.Print r.Address
Next r

In this lesson I will show you how to get selected rows of an Excel sheet using a macro. As developers we need to create various kinds of macros to fulfil user’s requirements. Sometimes users want to select rows manually in the excel sheet before running the macros. Then macro may need to detect the rows selected by the user before processing the data. For an example user may want to transfer selected rows to another file or sheet. Or combine data of selected rows. Those are a few examples where you need to get the selected rows. Now let’s learn how to get the selected rows using VBA.

Suppose a user has selected a one row like this.

One row is selected in Excel sheet

Then we can use this macro below to print the address of the row in the immediate window.

Sub GetSelectedRows()

     Dim SelectedRows As String
     Dim Rng As Range

     Set Rng = Selection
     SelectedRows = Rng.Address
     Debug.Print SelectedRows

End Sub

Here is the result of the above macro.

Result printed in the immediate window

What if the user selects multiple rows like this. 

User select contiguous rows

 

Then we will get the below result if we run the same macro.

Result of the contiguous rows

In the above examples, the result was a string. But usually we need to get the starting row and the ending row as numbers. Then only we can use those values in the next steps. So next let’s look at how we can get the starting row and the ending row. We can create two functions to get starting and ending rows. This is the function to get the starting row.

Function StartingRow() As Long

     Dim SelectedRows As String
     Dim Rng As Range

     Set Rng = Selection
     SelectedRows = Rng.Address
     StartingRow = Replace(Split(SelectedRows, «:»)(0), «$», «»)

End Function

In this function we have used two inbuilt functions. Split function and Replace function. Split function divides the string at the character “:”. For the above example, Split(SelectedRows, «:»)(0) will return $3
Then the replace function will remove the $ symbol.

And this is the function to get the ending row.

Function EndingRow() As Long

     Dim SelectedRows As String
     Dim Rng As Range

     Set Rng = Selection
     SelectedRows = Rng.Address
     EndingRow = Replace(Split(SelectedRows, «:»)(1), «$», «»)

End Function

Only difference is you have to replace 0 in the split function with 1. Then the split function will split the string at character : and take the second element. Now you can use the above functions in a subroutine.

Sub Main()

     Dim StartRow As Long
     Dim EndRow As Long

     StartRow = StartingRow()
     EndRow = EndingRow()
     Debug.Print «Start — «; StartRow
     Debug.Print «End — «; EndRow

End Sub

Here is the result you will get.

Return values of the function

But sometimes users may select non contiguous rows like this. 

Selection of non contiguous rows

Then our first macro (GetSelectedRows) will output this result.

Result for the non contiguous rows

But then our two functions will fail to output correct results. In a next lesson I will show you how to detect a non contiguous range and output the result as a two dimensional array. 

Sometimes you’ll want to select entire rows or columns, or even every cell in
a worksheet.  Here’s how:

Selecting Columns

You can do this using the Columns collection.  For
example:

Sub SelectColumns()

Columns(«B»).Select

Columns(«B:D»).Select

End Sub

The above macro would select column B, then columns
B
through to D:

Columns B to D selected

The result of running the above macro.

Note that you can select a single column by number too — for example,
Columns(2).Select
— but this method doesn’t work for a range of
columns.

Selecting Rows

You can select rows in the same way, but using the Rows
collection:

Sub SelectRows()

Rows(«2»).Select

Rows(«2:4»).Select

End Sub

The above routine would leave rows 2 through to 4 selected:

Rows 2 to 4 selected

The results of running the macro above.

Note that as for columns you can dispense with the quotation marks if you’re
selecting a single row.  So Rows(2).Select would also
select the second row.

 Selecting Every Cell in a Worksheet

In Excel you can select every single cell by clicking on the square at the
top left corner of a worksheet:

Selecting every cell

Click on the square shown to select every cell in a worksheet.

The VBA equivalent command to select every single cell in a sheet is:

Having seen how to select cells, rows and columns, it’s time to complete the
picture by showing some of the less commonly used selection commands. 

When working with Excel, most of your time is spent in the worksheet area – dealing with cells and ranges.

And if you want to automate your work in Excel using VBA, you need to know how to work with cells and ranges using VBA.

There are a lot of different things you can do with ranges in VBA (such as select, copy, move, edit, etc.).

So to cover this topic, I will break this tutorial into sections and show you how to work with cells and ranges in Excel VBA using examples.

Let’s get started.

All the codes I mention in this tutorial need to be placed in the VB Editor. Go to the ‘Where to Put the VBA Code‘ section to know how it works.

If you’re interested in learning VBA the easy way, check out my Online Excel VBA Training.

Selecting a Cell / Range in Excel using VBA

To work with cells and ranges in Excel using VBA, you don’t need to select it.

In most of the cases, you are better off not selecting cells or ranges (as we will see).

Despite that, it’s important you go through this section and understand how it works. This will be crucial in your VBA learning and a lot of concepts covered here will be used throughout this tutorial.

So let’s start with a very simple example.

Selecting a Single Cell Using VBA

If you want to select a single cell in the active sheet (say A1), then you can use the below code:

Sub SelectCell()
Range("A1").Select
End Sub

The above code has the mandatory ‘Sub’ and ‘End Sub’ part, and a line of code that selects cell A1.

Range(“A1”) tells VBA the address of the cell that we want to refer to.

Select is a method of the Range object and selects the cells/range specified in the Range object. The cell references need to be enclosed in double quotes.

This code would show an error in case a chart sheet is an active sheet. A chart sheet contains charts and is not widely used. Since it doesn’t have cells/ranges in it, the above code can’t select it and would end up showing an error.

Note that since you want to select the cell in the active sheet, you just need to specify the cell address.

But if you want to select the cell in another sheet (let’s say Sheet2), you need to first activate Sheet2 and then select the cell in it.

Sub SelectCell()
Worksheets("Sheet2").Activate
Range("A1").Select
End Sub

Similarly, you can also activate a workbook, then activate a specific worksheet in it, and then select a cell.

Sub SelectCell()
Workbooks("Book2.xlsx").Worksheets("Sheet2").Activate
Range("A1").Select
End Sub

Note that when you refer to workbooks, you need to use the full name along with the file extension (.xlsx in the above code). In case the workbook has never been saved, you don’t need to use the file extension.

Now, these examples are not very useful, but you will see later in this tutorial how we can use the same concepts to copy and paste cells in Excel (using VBA).

Just as we select a cell, we can also select a range.

In case of a range, it could be a fixed size range or a variable size range.

In a fixed size range, you would know how big the range is and you can use the exact size in your VBA code. But with a variable-sized range, you have no idea how big the range is and you need to use a little bit of VBA magic.

Let’s see how to do this.

Selecting a Fix Sized Range

Here is the code that will select the range A1:D20.

Sub SelectRange()
Range("A1:D20").Select
End Sub

Another way of doing this is using the below code:

Sub SelectRange()
Range("A1", "D20").Select
End Sub

The above code takes the top-left cell address (A1) and the bottom-right cell address (D20) and selects the entire range. This technique becomes useful when you’re working with variably sized ranges (as we will see when the End property is covered later in this tutorial).

If you want the selection to happen in a different workbook or a different worksheet, then you need to tell VBA the exact names of these objects.

For example, the below code would select the range A1:D20 in Sheet2 worksheet in the Book2 workbook.

Sub SelectRange()
Workbooks("Book2.xlsx").Worksheets("Sheet1").Activate
Range("A1:D20").Select
End Sub

Now, what if you don’t know how many rows are there. What if you want to select all the cells that have a value in it.

In these cases, you need to use the methods shown in the next section (on selecting variably sized range).

Selecting a Variably Sized Range

There are different ways you can select a range of cells. The method you choose would depend on how the data is structured.

In this section, I will cover some useful techniques that are really useful when you work with ranges in VBA.  

Select Using CurrentRange Property

In cases where you don’t know how many rows/columns have the data, you can use the CurrentRange property of the Range object.

The CurrentRange property covers all the contiguous filled cells in a data range.

Below is the code that will select the current region that holds cell A1.

Sub SelectCurrentRegion()
Range("A1").CurrentRegion.Select
End Sub

The above method is good when you have all data as a table without any blank rows/columns in it.

Cells and Ranges in VBA - currentregion property

But in case you have blank rows/columns in your data, it will not select the ones after the blank rows/columns. In the image below, the CurrentRegion code selects data till row 10 as row 11 is blank.

Cells and Ranges in VBA - currentregion property not selecting rows after blank

In such cases, you may want to use the UsedRange property of the Worksheet Object.

Select Using UsedRange Property

UsedRange allows you to refer to any cells that have been changed.

So the below code would select all the used cells in the active sheet.

Sub SelectUsedRegion()
ActiveSheet.UsedRange.Select
End Sub

Note that in case you have a far-off cell that has been used, it would be considered by the above code and all the cells till that used cell would be selected.

Select Using the End Property

Now, this part is really useful.

The End property allows you to select the last filled cell. This allows you to mimic the effect of Control Down/Up arrow key or Control Right/Left keys.

Let’s try and understand this using an example.

Suppose you have a dataset as shown below and you want to quickly select the last filled cells in column A.

The problem here is that data can change and you don’t know how many cells are filled. If you have to do this using keyboard, you can select cell A1, and then use Control + Down arrow key, and it will select the last filled cell in the column.

Now let’s see how to do this using VBA. This technique comes in handy when you want to quickly jump to the last filled cell in a variably-sized column

Sub GoToLastFilledCell()
Range("A1").End(xlDown).Select
End Sub

The above code would jump to the last filled cell in column A.

Similarly, you can use the End(xlToRight) to jump to the last filled cell in a row.

Sub GoToLastFilledCell()
Range("A1").End(xlToRight).Select
End Sub

Now, what if you want to select the entire column instead of jumping to the last filled cell.

You can do that using the code below:

Sub SelectFilledCells()
Range("A1", Range("A1").End(xlDown)).Select
End Sub

In the above code, we have used the first and the last reference of the cell that we need to select. No matter how many filled cells are there, the above code will select all.

Remember the example above where we selected the range A1:D20 by using the following line of code:

Range(“A1″,”D20”)

Here A1 was the top-left cell and D20 was the bottom-right cell in the range. We can use the same logic in selecting variably sized ranges. But since we don’t know the exact address of the bottom-right cell, we used the End property to get it.

In Range(“A1”, Range(“A1”).End(xlDown)), “A1” refers to the first cell and Range(“A1”).End(xlDown) refers to the last cell. Since we have provided both the references, the Select method selects all the cells between these two references.

Similarly, you can also select an entire data set that has multiple rows and columns.

The below code would select all the filled rows/columns starting from cell A1.

Sub SelectFilledCells()
Range("A1", Range("A1").End(xlDown).End(xlToRight)).Select
End Sub

In the above code, we have used Range(“A1”).End(xlDown).End(xlToRight) to get the reference of the bottom-right filled cell of the dataset.

Difference between Using CurrentRegion and End

If you’re wondering why use the End property to select the filled range when we have the CurrentRegion property, let me tell you the difference.

With End property, you can specify the start cell. For example, if you have your data in A1:D20, but the first row are headers, you can use the End property to select the data without the headers (using the code below).

Sub SelectFilledCells()
Range("A2", Range("A2").End(xlDown).End(xlToRight)).Select
End Sub

But the CurrentRegion would automatically select the entire dataset, including the headers.

So far in this tutorial, we have seen how to refer to a range of cells using different ways.

Now let’s see some ways where we can actually use these techniques to get some work done.

Copy Cells / Ranges Using VBA

As I mentioned at the beginning of this tutorial, selecting a cell is not necessary to perform actions on it. You will see in this section how to copy cells and ranges without even selecting these.

Let’s start with a simple example.

Copying Single Cell

If you want to copy cell A1 and paste it into cell D1, the below code would do it.

Sub CopyCell()
Range("A1").Copy Range("D1")
End Sub

Note that the copy method of the range object copies the cell (just like Control +C) and pastes it in the specified destination.

In the above example code, the destination is specified in the same line where you use the Copy method. If you want to make your code even more readable, you can use the below code:

Sub CopyCell()
Range("A1").Copy Destination:=Range("D1")
End Sub

The above codes will copy and paste the value as well as formatting/formulas in it.

As you might have already noticed, the above code copies the cell without selecting it. No matter where you’re on the worksheet, the code will copy cell A1 and paste it on D1.

Also, note that the above code would overwrite any existing code in cell D2. If you want Excel to let you know if there is already something in cell D1 without overwriting it, you can use the code below.

Sub CopyCell()
If Range("D1") <> "" Then
Response = MsgBox("Do you want to overwrite the existing data", vbYesNo)
End If
If Response = vbYes Then
Range("A1").Copy Range("D1")
End If
End Sub

Copying a Fix Sized Range

If you want to copy A1:D20 in J1:M20, you can use the below code:

Sub CopyRange()
Range("A1:D20").Copy Range("J1")
End Sub

In the destination cell, you just need to specify the address of the top-left cell. The code would automatically copy the exact copied range into the destination.

You can use the same construct to copy data from one sheet to the other.

The below code would copy A1:D20 from the active sheet to Sheet2.

Sub CopyRange()
Range("A1:D20").Copy Worksheets("Sheet2").Range("A1")
End Sub

The above copies the data from the active sheet. So make sure the sheet that has the data is the active sheet before running the code. To be safe, you can also specify the worksheet’s name while copying the data.

Sub CopyRange()
Worksheets("Sheet1").Range("A1:D20").Copy Worksheets("Sheet2").Range("A1")
End Sub

The good thing about the above code is that no matter which sheet is active, it will always copy the data from Sheet1 and paste it in Sheet2.

You can also copy a named range by using its name instead of the reference.

For example, if you have a named range called ‘SalesData’, you can use the below code to copy this data to Sheet2.

Sub CopyRange()
Range("SalesData").Copy Worksheets("Sheet2").Range("A1")
End Sub

If the scope of the named range is the entire workbook, you don’t need to be on the sheet that has the named range to run this code. Since the named range is scoped for the workbook, you can access it from any sheet using this code.

If you have a table with the name Table1, you can use the below code to copy it to Sheet2.

Sub CopyTable()
Range("Table1[#All]").Copy Worksheets("Sheet2").Range("A1")
End Sub

You can also copy a range to another Workbook.

In the following example, I copy the Excel table (Table1), into the Book2 workbook.

Sub CopyCurrentRegion()
Range("Table1[#All]").Copy Workbooks("Book2.xlsx").Worksheets("Sheet1").Range("A1")
End Sub

This code would work only if the Workbook is already open.

Copying a Variable Sized Range

One way to copy variable sized ranges is to convert these into named ranges or Excel Table and the use the codes as shown in the previous section.

But if you can’t do that, you can use the CurrentRegion or the End property of the range object.

The below code would copy the current region in the active sheet and paste it in Sheet2.

Sub CopyCurrentRegion()
Range("A1").CurrentRegion.Copy Worksheets("Sheet2").Range("A1")
End Sub

If you want to copy the first column of your data set till the last filled cell and paste it in Sheet2, you can use the below code:

Sub CopyCurrentRegion()
Range("A1", Range("A1").End(xlDown)).Copy Worksheets("Sheet2").Range("A1")
End Sub

If you want to copy the rows as well as columns, you can use the below code:

Sub CopyCurrentRegion()
Range("A1", Range("A1").End(xlDown).End(xlToRight)).Copy Worksheets("Sheet2").Range("A1")
End Sub

Note that all these codes don’t select the cells while getting executed. In general, you will find only a handful of cases where you actually need to select a cell/range before working on it.

Assigning Ranges to Object Variables

So far, we have been using the full address of the cells (such as Workbooks(“Book2.xlsx”).Worksheets(“Sheet1”).Range(“A1”)).

To make your code more manageable, you can assign these ranges to object variables and then use those variables.

For example, in the below code, I have assigned the source and destination range to object variables and then used these variables to copy data from one range to the other.

Sub CopyRange()
Dim SourceRange As Range
Dim DestinationRange As Range
Set SourceRange = Worksheets("Sheet1").Range("A1:D20")
Set DestinationRange = Worksheets("Sheet2").Range("A1")
SourceRange.Copy DestinationRange
End Sub

We start by declaring the variables as Range objects. Then we assign the range to these variables using the Set statement. Once the range has been assigned to the variable, you can simply use the variable.

Enter Data in the Next Empty Cell (Using Input Box)

You can use the Input boxes to allow the user to enter the data.

For example, suppose you have the data set below and you want to enter the sales record, you can use the input box in VBA. Using a code, we can make sure that it fills the data in the next blank row.

Sub EnterData()
Dim RefRange As Range
Set RefRange = Range("A1").End(xlDown).Offset(1, 0)
Set ProductCategory = RefRange.Offset(0, 1)
Set Quantity = RefRange.Offset(0, 2)
Set Amount = RefRange.Offset(0, 3)
RefRange.Value = RefRange.Offset(-1, 0).Value + 1
ProductCategory.Value = InputBox("Product Category")
Quantity.Value = InputBox("Quantity")
Amount.Value = InputBox("Amount")
End Sub

The above code uses the VBA Input box to get the inputs from the user, and then enters the inputs into the specified cells.

Note that we didn’t use exact cell references. Instead, we have used the End and Offset property to find the last empty cell and fill the data in it.

This code is far from usable. For example, if you enter a text string when the input box asks for quantity or amount, you will notice that Excel allows it. You can use an If condition to check whether the value is numeric or not and then allow it accordingly.

Looping Through Cells / Ranges

So far we can have seen how to select, copy, and enter the data in cells and ranges.

In this section, we will see how to loop through a set of cells/rows/columns in a range. This could be useful when you want to analyze each cell and perform some action based on it.

For example, if you want to highlight every third row in the selection, then you need to loop through and check for the row number. Similarly, if you want to highlight all the negative cells by changing the font color to red, you need to loop through and analyze each cell’s value.

Here is the code that will loop through the rows in the selected cells and highlight alternate rows.

Sub HighlightAlternateRows()
Dim Myrange As Range
Dim Myrow As Range
Set Myrange = Selection
For Each Myrow In Myrange.Rows
If Myrow.Row Mod 2 = 0 Then
Myrow.Interior.Color = vbCyan
End If
Next Myrow
End Sub

The above code uses the MOD function to check the row number in the selection. If the row number is even, it gets highlighted in cyan color.

Here is another example where the code goes through each cell and highlights the cells that have a negative value in it.

Sub HighlightAlternateRows()
Dim Myrange As Range
Dim Mycell As Range
Set Myrange = Selection
For Each Mycell In Myrange
If Mycell < 0 Then
Mycell.Interior.Color = vbRed
End If
Next Mycell
End Sub

Note that you can do the same thing using Conditional Formatting (which is dynamic and a better way to do this). This example is only for the purpose of showing you how looping works with cells and ranges in VBA.

Where to Put the VBA Code

Wondering where the VBA code goes in your Excel workbook?

Excel has a VBA backend called the VBA editor. You need to copy and paste the code in the VB Editor module code window.

Here are the steps to do this:

  1. Go to the Developer tab.vba cells and ranges - Developer Tab in ribbon
  2. Click on the Visual Basic option. This will open the VB editor in the backend.Click on Visual Basic
  3. In the Project Explorer pane in the VB Editor, right-click on any object for the workbook in which you want to insert the code. If you don’t see the Project Explorer, go to the View tab and click on Project Explorer.
  4. Go to Insert and click on Module. This will insert a module object for your workbook.Cells and Ranges in VBA - Module
  5. Copy and paste the code in the module window.Cells and Ranges in VBA - code paste

You May Also Like the Following Excel Tutorials:

  • Working with Worksheets using VBA.
  • Working with Workbooks using VBA.
  • Creating User-Defined Functions in Excel.
  • For Next Loop in Excel VBA – A Beginner’s Guide with Examples.
  • How to Use Excel VBA InStr Function (with practical EXAMPLES).
  • Excel VBA Msgbox.
  • How to Record a Macro in Excel.
  • How to Run a Macro in Excel.
  • How to Create an Add-in in Excel.
  • Excel Personal Macro Workbook | Save & Use Macros in All Workbooks.
  • Excel VBA Events – An Easy (and Complete) Guide.
  • Excel VBA Error Handling.
  • How to Sort Data in Excel using VBA (A Step-by-Step Guide).
  • 24 Useful Excel Macro Examples for VBA Beginners (Ready-to-use).

I’m going to start by reviewing a couple fundamentals about selecting ranges in Excel with VBA, then I’ll discuss methods for selecting ranges with variable row numbers.

Selecting Cells in Excel

One of the most common situations in Microsoft Excel is that you need to select a cell or a range of cells to perform an action. For example, even just to copy and paste content, you need to perform steps below one-by-one (I bet you never thought this was actually a complex task).

  1. Select the cell(s) to be copied
  2. Click on copy (or) ctrl + c
  3. Select the cell(s) into which the content needs to be pasted
  4. Click on paste (or) ctrl + v

In this process, we select one cell or multiple cells that are in continuous rows and columns. This continuous selection is called a “Range”. A range is generally identified by the starting cell reference in the left-side top corner and ending cell reference in the bottom right corner of the selection. For example, in the image below, the range is from C2 to E7. All the cells within this cell reference are selected.

Blank Excel worksheet with a range selected

The Range Expression

VBA offers a Range expression that can be used in selection of cells.

Syntax:

Range (“ < reference starting cell > : < reference ending cell >”)

(or)

Range ( Cells ( <row_number> , <col_number> ) , Cells ( <row_number> , <col_number> ) )

In other words, the range of cells selected in the image above can be expressed in any one of the following ways — for our example, we’ll assume that we are selecting the range on a sheet named “Wonders.”

Sheets("Wonders").Range("C2:E7").Select

Note that letters are used to represent column number and row is indicated by a number. There is a colon in between to two cell references and the entire parameter is encased in double quotes.

Sheets("Wonders").Range(Cells(2, 3), Cells(7, 5)).Select

In this case, double quotes are not used for the range. There is comma instead of the colon symbol, and the cell references are represented using the Cells expression and the row and column numbers.

Try it yourself. Name an Excel sheet “Wonders.” Try running the code below and check the “Wonders” sheet to see what has been selected.

Sub range_demo()
Sheets("Wonders").Range("B2:F6").Select
Sheets("Wonders").Range(Cells(2, 3), Cells(7, 5)).Select
End Sub

Variable row numbers in the Range expression

So far we’ve tried to select a range of cells knowing the exact references of two cells that form the range. Now, it is time to see how to insert a dynamic or varying row or column number in the same expression.

The way to do it is simply with concatenation using double quotes and the ampersand (&) symbol.

Let’s look at some examples.

Color a range of cells up to a dynamically changing last row

In the example below, let’s find the last used row and dynamically use that row in the Range expression. This example will color the selected cells in green.

Sub range_demo()

'declare variable
Dim lastrow As Integer

'initialize variable
lastrow = ActiveSheet.UsedRange.Rows.Count

'Use the variable in the range expression to select
Sheets("Wonders").Range("A2:C" &amp;amp;amp;amp; lastrow).Select

'colour the selected cells in green
With Selection.Interior
        .Pattern = xlSolid
        .PatternColorIndex = xlAutomatic
        .Color = 5296274 'green colour
End With

End Sub

Cell background color of range changed dynamically

Color the font of selected cells up to a specific row input by the user

Below is another example that uses the Cells expression to do the same thing. Here we will change the font color of the selected cells.

Sub range_demo()

'declare variable
Dim row_num As Integer

'initialize variable - enter 6 while running the code
row_num = InputBox("Enter the row number")

'Use the variable in the range expression to select only the first 5 rows of data - not the headers
Sheets("Wonders").Range(Cells(2, 1), Cells(row_num, 3)).Select

'colour the font of selected cells in white
With Selection.Font
        .ThemeColor = xlThemeColorDark1
        .TintAndShade = 0
End With

End Sub

Cell color formatted gray based on user input of range

Use a different runtime number in both cell references

In this example, we’re still not hardcoding the cell references. Three rows starting from the row number input by the user are formatted in “Bold.”

Sub range_demo()

'declare variable
Dim row_num As Integer

'initialize variable - enter 3 while running the code
row_num = InputBox("Enter the row number")

'Use the variable in the range expression to select only the first 3 rows of data starting from the row_num input by the user
Sheets("Wonders").Range(Cells(row_num, 1), Cells((row_num + 3), 3)).Select

'make the font of the selected cells to "Bold"
Selection.Font.Bold = True

End Sub

Cells formatted dynamically based on runtime input

Concatenating both cell references of a simple range expression

Sub range_demo()

'declare variable
Dim row_num As Integer

'initialize variable - enter 7 while running the code
row_num = InputBox("Enter the row number")

'Use the variable in the range expression to select only the first 3 rows of data starting from the row_num input by the user
Sheets("Wonders").Range("A" &amp;amp;amp;amp; row_num &amp;amp;amp;amp; ":C" &amp;amp;amp;amp; row_num + 2).Select

'make the font of the selected cells to "Italics"
Selection.Font.Italic = True

End Sub

Both cell references concatenated

Conclusion

The Range expression in VBA is very useful for calculating and formatting cells in MS Excel. Not just row numbers, but also column numbers can be dynamically inserted to make the best use of the expression. In other words, instead of hard coding the reference directly, we can use a variable that holds the number in the expression.

Ranges are a key concept in Excel, and knowing how to work with them is essential for anyone who wants to program or automate their work using Excel VBA. 

In this tutorial, we’ll take a look at how to work with Excel ranges in VBA. We’ll start by discussing what a Range object is. Then, we’ll look at the different ways of referencing a range. Lastly, we’ll explore various examples of how to work with ranges using VBA code.

Excel VBA: The Range object

The Excel VBA Range object is used to represent a range in a worksheet. A range can be a cell, a group of cells, or even all the 17,179,869,184 cells in a sheet.

When programming with Excel VBA, the Range object is going to be your best friend. That’s because much of your work will focus on manipulating data within sheets. Understanding how to work with the Range object will make it easier for you to perform various actions on cells, such as changing their values, sorting, or doing a copy-paste.

The following is the Excel object hierarchy:

Application > Workbook > Worksheet > Range

You can see that the Excel VBA Range object is a property of the Worksheet object. This means that you can access a range by specifying the name of the sheet and the cell address you want to work with. When you don’t specify a sheet name, by default Excel will look for the range in the active sheet. For example, if Sheet1 is active, then both of these lines will refer to the same cell range:

Range("A1") 
Worksheets("Sheet1").Range("A1")

Let’s have a closer look at how to reference a range in the section below. 

Figure 05. A SUMIFS VBA code basic example

Excel VBA Tutorial in 20 Minutes

Referencing a range of cells in Excel VBA

Referring to a Range object in Excel VBA can be done in several ways. We’ll discuss the basic syntax and some alternatives that you might want to use, depending on your needs.

Excel VBA: Syntax for specifying a cell range

To refer to a range that consists of one cell, for example, cell D5, you can use the syntax below: 

Range("D5")

To refer to a range of cells, you have two acceptable syntaxes. For example, A1 through D5 can be specified using any one below:

Range("A1:D5")
Range("A1", "D5")

To refer to a range outside the active sheet, you need to include the worksheet name. Here’s an example:

Worksheets("Sheet1").Range("A1:D5")

To refer to an entire row, for example, Row 5:

Range("5:5")

To refer to an entire column, for example, Column D:

Range("D:D")

Excel VBA also allows you to refer to multiple ranges at once by using a comma to separate each area. For example, see the below syntax used for referring to all ranges shown in the image:

Range("B2:D8, F4:G5")

Figure 2.1. Excel VBA referring to multiple ranges

Tip: Notice that all of the syntaxes above use double quotes to enclose the range address. To make it quicker for you to type, you can use shortcuts that involve using square brackets without quotes, as shown in the table below:

Syntax Shortcut
Range("D5") [D5]
Range("A1:D5") [A1:D5]
Range("5:5") [5:5]
Range("B2:D8, F4:G5") [B2:D8, F4:G5]

Excel VBA: Referencing a named range

You have probably already used named ranges in your worksheets. They can be found under Name Manager in the Formulas tab.

To refer to a range named MyRange, use the following code:

Range("MyRange")

Remember to enclose the range’s name in double quotes. Otherwise, Excel thinks that you’re referring to a variable. 

Alternatively, you can also use the shortcut syntax discussed previously. In this case, double quotes aren’t used:

[MyRange]

Excel VBA: Referencing a range using the Cells property

Another way to refer to a range is by using the Cells property. This property takes two arguments: 

Cells(Row, Column) 

You must use a numeric value for Row, but you may use either a numeric or string value for Column. Both of these lines refer to cell D5: 

Cells(5, "D") 
Cells(5, 4) 

The advantage of using the Cells property to refer to ranges becomes clear when you need to loop through rows or columns. You can create a more readable piece of code by using variables as the Cells arguments in a looping. 

Excel VBA: Referencing a range using the Offset property

The Offset property provides another handy means for referring to ranges. It allows you to refer to a cell based on the location of another cell, such as the active cell. 

Like the Cells property, the Offset property has two parameters. The first determines how many rows to offset, while the second represents the number of columns to offset. Here is the syntax:

Range.Offset(RowOffset, ColumnOffset)

For example, the following code refers to cell D5 from cell A1:

Range("A1").Offset(4,3)

Figure 2.4. Excel VBA An example of referencing a range using the Offset property

The negative numbers refer to cells that are above or below the range of values. For example, a -2 row offset refers to two rows above the range, and a -1 column offset refers to a column to the left of the range. The following example refers to cell A1:

Range("D3").Offset(-2, -3)

If you need to go over only a row or a column, but not both, you don’t have to enter both the row and the column parameters. You can also use 0 as one or both of the arguments. For example, the following lines refer to D5:

Range("D5").Offset(0, 0)
Range("D2").Offset(3, 0)
Range("G5").Offset(, -3)

Let’s take a look at some of the most common range examples. These examples will show you how to use VBA to select and manipulate ranges in your worksheets. Some of these examples are complete procedures, while others are code snippets that you can just copy-paste to your own Sub to try.

Excel VBA: Select a range of cells

To select a range of cells, use the Select method. 

The following line selects a range from A1 to D5 in the active worksheet:

Range("A1:D5").Select

To select a range from A1 to the active cell, use the following line: 

Range("A1", ActiveCell).Select

The following code selects from the active cell to 3 rows below the active cell and five columns to the right: 

Range(ActiveCell, ActiveCell.Offset(3, 5)).Select

It’s important to note that when you need to select a range on a specific worksheet, you need to ensure that the correct worksheet is active. Otherwise, an error will occur. For example, you want to select B2 to J5 on Sheet1. The following code will generate an error if Sheet1 is not active:

Worksheets("Sheet1").Range("B2:J5").Select

Instead, use these two lines of code to make your code work as expected:

Worksheets("Sheet1").Activate 
Range("B2:J5").Select

Excel VBA: Set values to a range

The following statement sets a value of 100 into cell C7 of the active worksheet:

Range("C7").Value = 100

The Value property allows you to represent the value of any cell in a worksheet. It’s a read/write property, so you can use it for both reading and changing values.

You can also set values of a range of any size. The following statement enters the text “Hello” into each cell in the range A1:C7 in Sheet2:

Worksheets("Sheet2").Range("A1:C7").Value = "Hello"

Value is the default property for a Range object. This means that if you don’t provide any properties in your range, Excel will use this Value property. 

Both of the following lines enter a value of 100 into cell C7 of the active worksheet: 

Range("C7").Value = 100
Range("C7") = 100

Excel VBA: Copy range to another sheet

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. 

Let’s say you have Orders data, as shown in the below screenshot, which is imported from Airtable every day using Coupler.io. This tool allows users to do it automatically on the schedule they want with just a few clicks and no coding required. 

Coupler.io data integration tool

In addition, they can combine data from other different sources (such as Jira, Mailchimp, etc.) into one destination for analysis purposes.

Figure 3.3. Excel VBA Copy range example

As you can see, the data starts from B2. You want to copy only range B2:C11 and paste them to Sheet2 at the same address. The following is an example Sub you can use:

Sub CopyRangeToAnotherSheet()
    Sheets("Sheet1").Activate
    Range("B2:C11").Select
    Selection.Copy
    
    Sheets("Sheet2").Activate
    Range("B2").Select
    ActiveSheet.Paste
End Sub

Alternatively, you can also use a single line of code as shown below:

Sub CopyRangeToAnotherSheet2()
    Worksheets("Sheet1").Range("B2:C11").Copy Worksheets("Sheet2").Range("B2")
End Sub

The above Sub procedure takes advantage of the fact that the Copy method can use an argument that corresponds to the destination range for the copy operation. Notice that actually, you don’t have to select a range before doing something with it.

Excel VBA: Dynamic range example

In many cases, you may need to copy a range of cells but don’t know exactly how many rows and columns it has. For example, if you use Coupler.io or other integration tools to import data from an external app into Excel on a daily schedule, the number of rows may change over time.

How can you determine this dynamic range? One solution is to use the CurrentRegion property. This property returns an Excel VBA Range object within its boundaries. As long as the data is surrounded by one empty row and one empty column, you can select it with CurrentRegion.

The following line selects the contiguous range around Cell B2:

Range("B2").CurrentRegion.Select

Figure 3.4.1. Excel VBA Dynamic range example 1

Now, let’s say you want to select only Columns B and C of the range, and from the second row, you can use the following line:

Range("B2", Range("C2").End(xlDown)).Select

Figure 3.4.2. Excel VBA Selecting columns in a dynamic range

You can now do whatever you want with your selected range — copy or move it to another sheet, format it, and so on.

If you want to find the last row of a used range using Excel VBA, it’s also possible without selecting anything. Here’s the line you can use to find the row number of Column B’s last row data:

' Find the row number of Column B's last row data
RowNumOfLastRow = Cells(Rows.Count, 2).End(xlUp).Row


' Result: 11
MsgBox RowNumOfLastRow

Excel VBA: Loop for each cell in a range 

For looping each cell in a range, the For Each loop is an excellent choice. This type of loop is great for looping through a collection of objects such as cells in a range, worksheets in a workbook, or other collections.

The following procedure shows how to loop through each cell in Range B2:K11. We use an object variable named Obj, which refers to the cell being processed. Within the loop, the code checks if the cell contains a formula and then sets its color to blue.

Sub LoopForEachCell()
    Dim obj As Range
    For Each obj In Range("B2:K11")
        If obj.HasFormula Then obj.Font.Color = vbBlue
    Next obj
End Sub

Excel VBA: Loop for each row in a range

When looping through rows (or columns), you can use the Cells property to refer to a range of cells. This makes your code more readable compared to when you’re using the Range syntax. 

For example, to loop for each row in range B2:K11 and bold all the cells from Column I to K, you might write a loop like this:

Sub LoopForEachRow()
    For i = 1 To 11
        Range("I" & i & ":K" & i).Font.Bold = True
    Next i
End Sub

Instead of typing in a range address, you can use the Cells property to make the loop easier to read and write. For example, the code below uses the Cells and Resize properties to find the required cell based on the active cell:

Sub LoopForEachRow2()
    For i = 1 To 11
        Cells(i, "I").Resize(, 3).Font.Bold = True
    Next i
End Sub

Excel VBA: Clear a range

There are three ways to clear a range in Excel VBA. 

The first is to use the Clear method, which will clear the entire range, including cell contents and formatting. 

The second is to use the ClearContents method, which will clear the contents of the range but leave the formatting intact. 

The third is to use the ClearFormats method, which will clear the formatting of the range but leave the contents intact.

For example, to clear a range B1 to M15, you can use one of the following lines of code below, based on your needs:

Range("B1:M15").Clear
Range("B1:M15").ClearContents
Range("B1:M15").ClearFormats

Excel VBA: Delete a range

When deleting a range, it differs from just clearing a range. That’s because Excel shifts the remaining cells around to fill up your deleted range. 

The code below deletes Row 5 using the Delete method:

Range("5:5").Delete

To delete a range that is not a complete row or column, you have to provide an argument (such as xlToLeft, xlUp — based on your needs) that indicates how Excel should shift the remaining cells.

For example, the following code deletes cell B2 to M10, then fills the resulting gap by shifting the other cells to the left:

Range("B2:M10").Delete xlToLeft

Excel VBA: Delete rows with a specific condition in a range

You can also use a VBA code to delete rows with a specific condition. For example, let’s try to delete all the rows with a discount of 0 from the below sheet:

Figure 3.9. Excel VBA example Delete range with a condition

Here’s an example Sub you may want to use:

Sub DeleteWithCondition()
    For i = 3 To 11
        If Cells(i, "F").Value = 0 Then
            Cells(i, 1).EntireRow.Delete
        End If
    Next i
End Sub

The above code loops from Row 3 to 11. In each loop, it checks the discount value in Column F and removes the entire row if the value equals 0.

Excel VBA: Find values in a range 

With the below data, suppose you want to find if there is an order with OrderNumber equal to 1003320 and output its cell address. 

Figure 3.10. Excel VBA Find a value in a range example

You can use the Find method in this case, as shown in the below code:

Sub FindOrder()
    Dim Rng As Range
     
    Set Rng = Range("B3:B11").Find("1003320")
     
    If Rng Is Nothing Then
        MsgBox "The OrderNumber not found."
    Else
        MsgBox Rng.Address
    End If

End Sub

The output of the above code will be the first occurrence of the search value in the specified range. If the value is not found, a message box showing info that the order is not found will appear.

Excel VBA: Add alрhаbеtѕ using Rаngе .Offset

The following is an example of a Sub that adds alphabets A-Z in a range. The code uses Offset to refer to a cell below the active cell in a loop.

Sub AddAlphabetsAZ()
    Dim i As Integer
    
    ' Use 97 To 122 for lowercase letters
    For i = 65 To 90
        ActiveCell.Value = Chr(i)
        ActiveCell.Offset(1, 0).Select
    Next i
End Sub

To use the Sub, ѕеlесt a сеll where you want tо start thе alphabets. Then, run it by pressing F5. The code will insert A-Z to the cells downward. 

Excel VBA: Add auto-numbers to a range with a variable from user input

Juѕt lіkе inserting alphabets as shown in the previous example, you саn аlѕо іnѕеrt auto-numbers іn уоur worksheet automatically. This can be helpful when you work with large data.

The following is an example of a Sub that adds auto-numbers to your Excel sheet:

Sub AddAutoNumbers()
    Dim i As Integer
    
    On Error GoTo ErrorHandler
    
    i = InputBox("Enter the maximum number: ", "Enter a value")
    
    For i = 1 To i
        ActiveCell.Value = i
        ActiveCell.Offset(1, 0).Select
    Next i
    
ErrorHandler:
    Exit Sub
End Sub

Tо uѕе the соdе, уоu need tо ѕеlесt the сеll frоm where you want tо start thе auto-numbеrѕ. Then, run the Sub. In the message box that appears, enter the maximum value for the auto-numbers and сlісk OK.

Figure 3.12. Excel VBA set a range using a variable example

Excel VBA: Sum a range 

Imagine that you have written a Sub procedure to import Orders.csv into an Excel sheet:

By the way, you can automate import of CSV to Excel without any coding if you use Coupler.io

Figure 3.13. Excel VBA Sum a range example

You want to sum up all the discount values and put the result in J12. The following code that utilizes the Sum worksheet function would handle that: 

Sub GetTotalDiscount()
    Range("J12") = WorksheetFunction.Sum(Range("J2:J10"))
End Sub

Excel VBA: Sort a range 

The Sort method sorts values in a range based on the criteria you provide.

Suppose you have the following sheet:

Figure 3.14. Excel VBA Sort a range example

To sort the above data based оn thе vаluеѕ іn Column D, you can use the following code:

Sub SortBySingleColumn()
    Range("A1:E10").Sort Key1:=Range("D1"), Order1:=xlAscending, Header:=xlYes
End Sub

You can also sort the range by multiple columns. For example, to sort by Column B and Column D, here’s an example code you can use:

Sub SortByMultipleColumns()
    Range("A1:E10").Sort _
        Key1:=Range("B1"), Order1:=xlAscending, _
        Key2:=Range("D1"), Order2:=xlAscending, _
        Header:=xlYes
End Sub

Here are the arguments used in the above methods:

  • Kеу: It specifies the field you want to use in ѕоrting thе data. 
  • Ordеr: It ѕресіfies whеthеr уоu wаnt tо sort the dаtа іn аѕсеndіng or dеѕсеndіng order. 
  • Header: It spесіfies whеthеr уоur data hаѕ hеаdеrѕ оr nоt.

Excel VBA: Range to array

Arrays are powerful because they can actually make the code run faster. Especially when working with large data, you can use arrays to make all the processing happen in memory and then write the data to the sheet once.

For example, suppose you have the following sheet:

Figure 3.15.1. Excel VBA Sort range example

The following Sub uses a variable X, which is a Variant data type, to store the value of Range A2:E10. Variants can hold any type of data, including arrays. 

Sub RangeToArray()
    Dim X As Variant
    X = Range("A2:E10")
End Sub

You can then treat the X variable as though it were an array. The following line returns the value of cell A6:

MsgBox X(5, 1)
' Result: 1003320

Now, let’s say you want to calculate the total order using the following calculation:

Quantity * Price - Discount

Rather than doing calculation and writing the result for each row using a looping, you can store the calculation result in an array OrderTotal as shown in the below code and write the result once:

Sub CalculateTotalOrder()
    Dim X As Variant, OrderTotal As Variant
    X = Range("A2:E10")
    
    ReDim OrderTotal(UBound(X))
    
    For i = LBound(X) To UBound(X)
        OrderTotal(i - 1) = X(i, 3) * X(i, 4) - X(i, 5)
    Next i
    
    Range("F1") = "OrderTotal"
    
    Range("F2").Resize(UBound(OrderTotal)) = _
        Application.Transpose(OrderTotal)
    
End Sub

Here’s the final result:

Figure 3.15.2. Excel VBA Sort range result

Subscript out of range: Excel VBA Runtime error 9

This error message often happens when you try to access a range of cells in a worksheet that has been deleted or renamed.

Figure 4. Excel VBA Subscript out of range error

Let’s say your code expected a worksheet named Setting. For some reason, this sheet is renamed Settings. So, the error occurs every time the below Sub runs:

Sub GetSettings()
    Worksheets("Setting").Select
    x = Range("A1").Value
End Sub

To prevent the runtime error happening again, you may want to add an error handler code like this below:

Sub GetSettings()
    On Error Resume Next

    ws = Worksheets("Setting")
    Name = ws.Name
    
    If Not Err.Number = 0 Then
        MsgBox "Expected to find a Setting worksheet, but it is missing."
        Exit Sub
    End If
    On Error GoTo 0
    
    ws.Select
    x = Range("A1").Value
End Sub

Excel VBA Range — Final words

Thank you for reading our Excel VBA Range tutorial. We hope that you’ve found it helpful! And if there’s anything else about Excel programming or other topics that interest you, be sure to check out our other Excel tutorials.

In addition, you may find that Coupler.io is a valuable tool for you if you’re looking for an easy way to pull and combine your data from multiple sources into one destination for analysis and reporting. This tool also lets you specify the range address of your imported data so you can keep all of your calculations (including. formulas) in the sheets.

Thanks again for reading, and happy coding!

  • Fitrianingrum Seto

    Senior analyst programmer

Back to Blog

Focus on your business

goals while we take care of your data!

Try Coupler.io

Понравилась статья? Поделить с друзьями:
  • Select one cell in excel vba
  • Select number vba word
  • Select line in word
  • Select language in word
  • Select in excel from row