A Range is a group of selected Cells in an Excel worksheet. A Range can be rectangular or square in shape. You can select a Range by left-click, drag and release the mouse over the cells you want to select.
You can distinguish the Range in a worksheet by the hi-lighted Cells. You can see from the below image that, the color of one Cell inside the Range is not hi-lighted. This is the Active Cell of the Range. Normally, this is the first cell you clicked while selecting the Range.
For Example; you want to select the Range from Cell address D6 to G12. To select Range from D6 to G12, click and drag from Cell address D6 through Cell address G12 with mouse (or vice versa).
A Cell is identified by a Cell address. Similarly, a Range in Excel worksheet is identified by a Range Address. The syntax for forming an Excel Range address is as below.
[Cell address of Top-Left cell in the Range]:[Cell address Bottom-Right Cell in the Range]
Thus the Range address of the Range in above example is is D6:G12.
The selected Range in Excel will be removed if you click on Excel worksheet or press any arrow in keyboard.
In this Article
- Ranges and Cells in VBA
- Cell Address
- Range of Cells
- Writing to Cells
- Reading from Cells
- Non Contiguous Cells
- Intersection of Cells
- Offset from a Cell or Range
- Setting Reference to a Range
- Resize a Range
- OFFSET vs Resize
- All Cells in Sheet
- UsedRange
- CurrentRegion
- Range Properties
- Last Cell in Sheet
- Last Used Row Number in a Column
- Last Used Column Number in a Row
- Cell Properties
- Copy and Paste
- AutoFit Contents
- More Range Examples
- For Each
- Sort
- Find
- Range Address
- Range to Array
- Array to Range
- Sum Range
- Count Range
Ranges and Cells in VBA
Excel spreadsheets store data in Cells. Cells are arranged into Rows and Columns. Each cell can be identified by the intersection point of it’s row and column (Exs. B3 or R3C2).
An Excel Range refers to one or more cells (ex. A3:B4)
Cell Address
A1 Notation
In A1 notation, a cell is referred to by it’s column letter (from A to XFD) followed by it’s row number(from 1 to 1,048,576). This is called a cell address.
In VBA you can refer to any cell using the Range Object.
' Refer to cell B4 on the currently active sheet
MsgBox Range("B4")
' Refer to cell B4 on the sheet named 'Data'
MsgBox Worksheets("Data").Range("B4")
' Refer to cell B4 on the sheet named 'Data' in another OPEN workbook
' named 'My Data'
MsgBox Workbooks("My Data").Worksheets("Data").Range("B4")
R1C1 Notation
In R1C1 Notation a cell is referred by R followed by Row Number then letter ‘C’ followed by the Column Number. eg B4 in R1C1 notation will be referred by R4C2. In VBA you use the Cells Object to use R1C1 notation:
' Refer to cell R[6]C[4] i.e D6
Cells(6, 4) = "D6"
Range of Cells
A1 Notation
To refer to a more than one cell use a “:” between the starting cell address and last cell address. The following will refer to all the cells from A1 to D10:
Range("A1:D10")
R1C1 Notation
To refer to a more than one cell use a “,” between the starting cell address and last cell address. The following will refer to all the cells from A1 to D10:
Range(Cells(1, 1), Cells(10, 4))
Writing to Cells
To write values to a cell or contiguous group of cells, simple refer to the range, put an = sign and then write the value to be stored:
' Store F5 in cell with Address F6
Range("F6") = "F6"
' Store E6 in cell with Address R[6]C[5] i.e E6
Cells(6, 5) = "E6"
' Store A1:D10 in the range A1:D10
Range("A1:D10") = "A1:D10"
' or
Range(Cells(1, 1), Cells(10, 4)) = "A1:D10"
Reading from Cells
To read values from cells, simple refer to the variable to store the values, put an = sign and then refer to the range to be read:
Dim val1
Dim val2
' Read from cell F6
val1 = Range("F6")
' Read from cell E6
val2 = Cells(6, 5)
MsgBox val1
Msgbox val2
Note: To store values from a range of cells, you need to use an Array instead of a simple variable.
Non Contiguous Cells
To refer to non contiguous cells use a comma between the cell addresses:
' Store 10 in cells A1, A3, and A5
Range("A1,A3,A5") = 10
' Store 10 in cells A1:A3 and D1:D3)
Range("A1:A3, D1:D3") = 10
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!
Learn More
Intersection of Cells
To refer to non contiguous cells use a space between the cell addresses:
' Store 'Col D' in D1:D10
' which is Common between A1:D10 and D1:F10
Range("A1:D10 D1:G10") = "Col D"
Offset from a Cell or Range
Using the Offset function, you can move the reference from a given Range (cell or group of cells) by the specified number_of_rows, and number_of_columns.
Offset Syntax
Range.Offset(number_of_rows, number_of_columns)
Offset from a cell
' OFFSET from a cell A1
' Refer to cell itself
' Move 0 rows and 0 columns
Range("A1").Offset(0, 0) = "A1"
' Move 1 rows and 0 columns
Range("A1").Offset(1, 0) = "A2"
' Move 0 rows and 1 columns
Range("A1").Offset(0, 1) = "B1"
' Move 1 rows and 1 columns
Range("A1").Offset(1, 1) = "B2"
' Move 10 rows and 5 columns
Range("A1").Offset(10, 5) = "F11"
Offset from a Range
' Move Reference to Range A1:D4 by 4 rows and 4 columns
' New Reference is E5:H8
Range("A1:D4").Offset(4,4) = "E5:H8"
Setting Reference to a Range
To assign a range to a range variable: declare a variable of type Range then use the Set command to set it to a range. Please note that you must use the SET command as RANGE is an object:
' Declare a Range variable
Dim myRange as Range
' Set the variable to the range A1:D4
Set myRange = Range("A1:D4")
' Prints $A$1:$D$4
MsgBox myRange.Address
VBA Programming | Code Generator does work for you!
Resize a Range
Resize method of Range object changes the dimension of the reference range:
Dim myRange As Range
' Range to Resize
Set myRange = Range("A1:F4")
' Prints $A$1:$E$10
Debug.Print myRange.Resize(10, 5).Address
Top-left cell of the Resized range is same as the top-left cell of the original range
Resize Syntax
Range.Resize(number_of_rows, number_of_columns)
OFFSET vs Resize
Offset does not change the dimensions of the range but moves it by the specified number of rows and columns. Resize does not change the position of the original range but changes the dimensions to the specified number of rows and columns.
All Cells in Sheet
The Cells object refers to all the cells in the sheet (1048576 rows and 16384 columns).
' Clear All Cells in Worksheets
Cells.Clear
UsedRange
UsedRange property gives you the rectangular range from the top-left cell used cell to the right-bottom used cell of the active sheet.
Dim ws As Worksheet
Set ws = ActiveSheet
' $B$2:$L$14 if L2 is the first cell with any value
' and L14 is the last cell with any value on the
' active sheet
Debug.Print ws.UsedRange.Address
CurrentRegion
CurrentRegion property gives you the contiguous rectangular range from the top-left cell to the right-bottom used cell containing the referenced cell/range.
Dim myRange As Range
Set myRange = Range("D4:F6")
' Prints $B$2:$L$14
' If there is a filled path from D4:F16 to B2 AND L14
Debug.Print myRange.CurrentRegion.Address
' You can refer to a single starting cell also
Set myRange = Range("D4") ' Prints $B$2:$L$14
AutoMacro | Ultimate VBA Add-in | Click for Free Trial!
Range Properties
You can get Address, row/column number of a cell, and number of rows/columns in a range as given below:
Dim myRange As Range
Set myRange = Range("A1:F10")
' Prints $A$1:$F$10
Debug.Print myRange.Address
Set myRange = Range("F10")
' Prints 10 for Row 10
Debug.Print myRange.Row
' Prints 6 for Column F
Debug.Print myRange.Column
Set myRange = Range("E1:F5")
' Prints 5 for number of Rows in range
Debug.Print myRange.Rows.Count
' Prints 2 for number of Columns in range
Debug.Print myRange.Columns.Count
Last Cell in Sheet
You can use Rows.Count and Columns.Count properties with Cells object to get the last cell on the sheet:
' Print the last row number
' Prints 1048576
Debug.Print "Rows in the sheet: " & Rows.Count
' Print the last column number
' Prints 16384
Debug.Print "Columns in the sheet: " & Columns.Count
' Print the address of the last cell
' Prints $XFD$1048576
Debug.Print "Address of Last Cell in the sheet: " & Cells(Rows.Count, Columns.Count)
Last Used Row Number in a Column
END property takes you the last cell in the range, and End(xlUp) takes you up to the first used cell from that cell.
Dim lastRow As Long
lastRow = Cells(Rows.Count, "A").End(xlUp).Row
Last Used Column Number in a Row
Dim lastCol As Long
lastCol = Cells(1, Columns.Count).End(xlToLeft).Column
END property takes you the last cell in the range, and End(xlToLeft) takes you left to the first used cell from that cell.
You can also use xlDown and xlToRight properties to navigate to the first bottom or right used cells of the current cell.
AutoMacro | Ultimate VBA Add-in | Click for Free Trial!
Cell Properties
Common Properties
Here is code to display commonly used Cell Properties
Dim cell As Range
Set cell = Range("A1")
cell.Activate
Debug.Print cell.Address
' Print $A$1
Debug.Print cell.Value
' Prints 456
' Address
Debug.Print cell.Formula
' Prints =SUM(C2:C3)
' Comment
Debug.Print cell.Comment.Text
' Style
Debug.Print cell.Style
' Cell Format
Debug.Print cell.DisplayFormat.NumberFormat
Cell Font
Cell.Font object contains properties of the Cell Font:
Dim cell As Range
Set cell = Range("A1")
' Regular, Italic, Bold, and Bold Italic
cell.Font.FontStyle = "Bold Italic"
' Same as
cell.Font.Bold = True
cell.Font.Italic = True
' Set font to Courier
cell.Font.FontStyle = "Courier"
' Set Font Color
cell.Font.Color = vbBlue
' or
cell.Font.Color = RGB(255, 0, 0)
' Set Font Size
cell.Font.Size = 20
Copy and Paste
Paste All
Ranges/Cells can be copied and pasted from one location to another. The following code copies all the properties of source range to destination range (equivalent to CTRL-C and CTRL-V)
'Simple Copy
Range("A1:D20").Copy
Worksheets("Sheet2").Range("B10").Paste
'or
' Copy from Current Sheet to sheet named 'Sheet2'
Range("A1:D20").Copy destination:=Worksheets("Sheet2").Range("B10")
Paste Special
Selected properties of the source range can be copied to the destination by using PASTESPECIAL option:
' Paste the range as Values only
Range("A1:D20").Copy
Worksheets("Sheet2").Range("B10").PasteSpecial Paste:=xlPasteValues
Here are the possible options for the Paste option:
' Paste Special Types
xlPasteAll
xlPasteAllExceptBorders
xlPasteAllMergingConditionalFormats
xlPasteAllUsingSourceTheme
xlPasteColumnWidths
xlPasteComments
xlPasteFormats
xlPasteFormulas
xlPasteFormulasAndNumberFormats
xlPasteValidation
xlPasteValues
xlPasteValuesAndNumberFormats
AutoFit Contents
Size of rows and columns can be changed to fit the contents using AutoFit:
' Change size of rows 1 to 5 to fit contents
Rows("1:5").AutoFit
' Change size of Columns A to B to fit contents
Columns("A:B").AutoFit
More Range Examples
It is recommended that you use Macro Recorder while performing the required action through the GUI. It will help you understand the various options available and how to use them.
AutoMacro | Ultimate VBA Add-in | Click for Free Trial!
For Each
It is easy to loop through a range using For Each construct as show below:
For Each cell In Range("A1:B100")
' Do something with the cell
Next cell
At each iteration of the loop one cell in the range is assigned to the variable cell and statements in the For loop are executed for that cell. Loop exits when all the cells are processed.
Sort
Sort is a method of Range object. You can sort a range by specifying options for sorting to Range.Sort. The code below will sort the columns A:C based on key in cell C2. Sort Order can be xlAscending or xlDescending. Header:= xlYes should be used if first row is the header row.
Columns("A:C").Sort key1:=Range("C2"), _
order1:=xlAscending, Header:=xlYes
Find
Find is also a method of Range Object. It find the first cell having content matching the search criteria and returns the cell as a Range object. It return Nothing if there is no match.
Use FindNext method (or FindPrevious) to find next(previous) occurrence.
Following code will change the font to “Arial Black” for all cells in the range which start with “John”:
For Each c In Range("A1:A100")
If c Like "John*" Then
c.Font.Name = "Arial Black"
End If
Next c
Following code will replace all occurrences of “To Test” to “Passed” in the range specified:
With Range("a1:a500")
Set c = .Find("To Test", LookIn:=xlValues)
If Not c Is Nothing Then
firstaddress = c.Address
Do
c.Value = "Passed"
Set c = .FindNext(c)
Loop While Not c Is Nothing And c.Address <> firstaddress
End If
End With
It is important to note that you must specify a range to use FindNext. Also you must provide a stopping condition otherwise the loop will execute forever. Normally address of the first cell which is found is stored in a variable and loop is stopped when you reach that cell again. You must also check for the case when nothing is found to stop the loop.
Range Address
Use Range.Address to get the address in A1 Style
MsgBox Range("A1:D10").Address
' or
Debug.Print Range("A1:D10").Address
Use xlReferenceStyle (default is xlA1) to get addres in R1C1 style
MsgBox Range("A1:D10").Address(ReferenceStyle:=xlR1C1)
' or
Debug.Print Range("A1:D10").Address(ReferenceStyle:=xlR1C1)
This is useful when you deal with ranges stored in variables and want to process for certain addresses only.
AutoMacro | Ultimate VBA Add-in | Click for Free Trial!
Range to Array
It is faster and easier to transfer a range to an array and then process the values. You should declare the array as Variant to avoid calculating the size required to populate the range in the array. Array’s dimensions are set to match number of values in the range.
Dim DirArray As Variant
' Store the values in the range to the Array
DirArray = Range("a1:a5").Value
' Loop to process the values
For Each c In DirArray
Debug.Print c
Next
Array to Range
After processing you can write the Array back to a Range. To write the Array in the example above to a Range you must specify a Range whose size matches the number of elements in the Array.
Use the code below to write the Array to the range D1:D5:
Range("D1:D5").Value = DirArray
Range("D1:H1").Value = Application.Transpose(DirArray)
Please note that you must Transpose the Array if you write it to a row.
Sum Range
SumOfRange = Application.WorksheetFunction.Sum(Range("A1:A10"))
Debug.Print SumOfRange
You can use many functions available in Excel in your VBA code by specifying Application.WorkSheetFunction. before the Function Name as in the example above.
Count Range
' Count Number of Cells with Numbers in the Range
CountOfCells = Application.WorksheetFunction.Count(Range("A1:A10"))
Debug.Print CountOfCells
' Count Number of Non Blank Cells in the Range
CountOfNonBlankCells = Application.WorksheetFunction.CountA(Range("A1:A10"))
Debug.Print CountOfNonBlankCells
Written by: Vinamra Chandra
How to use VBA Range.Address method?
Range.Address is used to get the cell address for simple local reference (ex. $A$1) or reference style notation for cell references (ex. A1 or R1C1 format). It can also be used to get the range address which includes the workbook name and worksheet name.
Syntax
expression .Address(RowAbsolute, ColumnAbsolute, ReferenceStyle, External, RelativeTo)
expression A variable that represents a Range object.
Parameters
Name | Required/Optional | Data Type | Description | ||
RowAbsolute | Optional | Variant |
|
||
ColumnAbsolute | Optional | Variant | True to return the column part of the reference as an absolute reference. The default value is True. | ||
ReferenceStyle | Optional | XlReferenceStyle | The reference style. The default value is xlA1. | ||
External | Optional | Variant |
|
||
RelativeTo | Optional | Variant | If RowAbsolute and ColumnAbsolute are False, and ReferenceStyle is xlR1C1, you must include a starting point for the relative reference. This argument is a Range object that defines the starting point. |
Below are the different sample codes:
- To simply display the local reference of the cell address
Sub Range_Address1() Set MyRange = Worksheets("021817").Cells(1, 1) MsgBox MyRange.Address() ' $A$1 End Sub
- To simply display the absolute address of the cell
Sub Range_Address2() Set MyRange = Worksheets("021817").Cells(1, 1) MsgBox MyRange.Address(RowAbsolute:=False) ' $A1 End Sub
- To display the reference style of the cell address. This simply means using the combination of both column letter and row number.
Sub Range_Address3() Set MyRange = Worksheets("021817").Cells(1, 1) MsgBox MyRange.Address(ReferenceStyle:=xlR1C1) ' R1C1 End Sub
- To display the cell address including workbook and worksheet name
Sub Range_Address4() Set MyRange = Worksheets("021817").Cells(1, 1) MsgBox MyRange.Address(External:=True) 'Address includes workbook and worksheet name End Sub
- Using the combined parameters
Sub Range_Address5() Set MyRange = Worksheets("021817").Cells(1, 1) MsgBox MyRange.Address(ReferenceStyle:=xlR1C1, _ RowAbsolute:=False, _ ColumnAbsolute:=False, _ RelativeTo:=Worksheets(1).Cells(3, 3)) ' R[-2]C[-2] End Sub
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:
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:
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
To 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.
To 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
If 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.
Similarly 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
The 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
The 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
The 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.
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
The Delete function
The 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
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
Every 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.
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
Merged 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:
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:
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 example the goal is to return the full address of a range or named range as text. The purpose of this formula is informational, not functional. It provides a way to inspect the current range for a named range, an Excel Table, or even the result of a formula. The core of the solutions explained below is the ADDRESS function, which returns a cell address based on a given row and column. The formula gets somewhat complicated because we need to use ADDRESS twice, and because there is a lot of busy work in collecting the coordinates we need to provide to ADDRESS. See below for a more elegant formula that takes advantage of the LET function and the TAKE function in Excel 365. This version can also report the range returned by another function (like OFFSET).
Note: the CELL function is another way to get the address for a cell. However, CELL does not provide a way to choose a relative or absolute format like the ADDRESS function does. In addition, CELL is a volatile function and can cause performance problems in large or complex worksheets. For those reasons, I have avoided it in this example.
Background
The links below provide more details about Excel Tables and named ranges:
- How to create an Excel Table (video)
- How to create a named range (video)
- How to create a dynamic named range with a table (video)
Demo
The animation below shows how the formula responds when a Table named «data» is resized. In the worksheet, DA stands for Dynamic Array version of Excel and Legacy stands for older versions of Excel. See below for more information about the dynamic array version.
The basic idea
The basic idea of this formula is to get the coordinates of the first (upper left) cell in a range and the last (lower right) cell in a range, then use these coordinates to create cell references, then join the references together with concatenation. The formula itself looks complicated and scary:
=ADDRESS(@ROW(data),@COLUMN(data),4)&":"&ADDRESS(@ROW(data)+ROWS(data)-1,@COLUMN(data)+COLUMNS(data)-1,4)
However, most of what you see is the «busy work» of collecting the coordinates with the ROW, ROWS, COLUMN, and COLUMNS functions. Once that work is done, the formula simplifies to this:
=ADDRESS(5,2,4)&":"&ADDRESS(16,4,4)
The ADDRESS function then creates a reference to the first and last cell in the range, and the two references are joined together. That’s it. The rest of the problem is the details of collecting the coordinates needed by the ADDRESS function.
ROW and COLUMN functions
The ROW and COLUMN functions simply return coordinates. For example, if we give ROW and COLUMN cell B5 as a reference, we get back coordinate numbers:
=ROW(B5) // returns 5
=COLUMN(B5) // returns 2
Notice that COLUMN returns a number, not a letter: column A, is 1, column B is 2, column C is 3, etc.
ROWS and COLUMNS functions
The ROWS and COLUMNS functions return counts. For example, if we give ROWS and COLUMNS the range B5:D16, we get back the number of rows and the number of columns in the range:
=ROWS(B5:D16) // returns 12
=COLUMNS(B5:D16) // returns 3
ADDRESS function
The ADDRESS function returns the address for a cell based on a given row and column number as text. For example:
=ADDRESS(1,1) // returns "$A$1"
=ADDRESS(5,2) // returns "$B$5"
Note that ADDRESS returns an address as an absolute reference by default. However, by providing 4 for the optional argument abs_num, ADDRESS will return a relative reference:
=ADDRESS(1,1,4) // returns "A1"
=ADDRESS(5,2,4) // returns "B5"
In this problem, we need to build up an address for a range in two parts (1) a reference to the first cell in the range and (2) a reference to the last cell in a range. To get the address for the first cell in the range, we use this formula:
=ADDRESS(@ROW(data),@COLUMN(data))
Note: data is the named range B5:E16.
As mentioned above, the ROW function and the COLUMN function return coordinates: ROW returns a row number, and COLUMN returns a column number. In this case however, we are giving ROW and COLUMN the range data, not a single cell. As a result, we get back an array of numbers:
=ROW(data) // returns {5;6;7;8;9;10;11;12;13;14;15;16}
=COLUMN(data) // returns {2,3,4,5}
In other words, ROW returns all row numbers for data (B5:D15), and COLUMN returns all column numbers for data. This is where the formula gets a bit complicated due to Excel version differences.
Although ROW and COLUMN return multiple results, older versions of Excel will automatically limit the results to the first value only. This works fine for the problem at hand, because we only want the first value. However, in the dynamic version of Excel, multiple results are not automatically limited, because formulas can spill results onto the worksheet. We don’t want this behavior in this case, so we use the implicit intersection operator (@) to limit the output from ROW and COLUMN to one value only:
=@ROW(data) // returns 5
=@COLUMN(data) // returns 2
In effect, this mimics the behavior in Legacy Excel where formulas that return more than one result display one result only. Note that the implicit intersection operator (@) is not required in Legacy Excel. In fact, if you try to add the @ in an older version of Excel, Excel will simply remove it. However, it is required in the current version of Excel.
Returning to the formula, ROW and COLUMN return their results directly to ADDRESS as the row_num and column_num arguments. With abs_num provided as 4 (relative), ADDRESS returns the text «B5».
=ADDRESS(5,2,4) // returns "B5"
To get the last cell in the range, we use the ADDRESS function again like this:
ADDRESS(@ROW(data)+ROWS(data)-1,@COLUMN(data)+COLUMNS(data)-1,4)
Essentially, we follow the same idea as above, using ROW and COLUMN to get the last row and last column of the range. However we also calculate the total number of rows with the ROWS function and the total number of columns with the COLUMNS function:
=ROWS(data) // returns 12
=COLUMNS(data) // returns 4
Then we do some simple math to calculate the row and column number of the last cell. We add the row count to the starting row, and add the column count to the starting column, then subtract 1 to get the correct coordinates for the last cell:
=ADDRESS(@ROW(data)+ROWS(data)-1,@COLUMN(data)+COLUMNS(data)-1,4)
=ADDRESS(5+12-1,2+4-1,4)
=ADDRESS(16,5,4)
="E16"
With abs_num set to 4. ADDRESS returns «E16», the address of the last cell in data as text. At this point, we have the address for the first cell and the address for the last cell. The only thing left to do is concatenate them together separated by a colon:
="B5"&":"&"E16"
="B5:E16"
More elegant formula
Although the formula above works fine, it is cumbersome and redundant. New array functions in Excel make it possible to solve the problem with a more elegant formula like this:
=LET(
first,TAKE(rng,1,1),
last,TAKE(rng,-1,-1),
ADDRESS(ROW(first),COLUMN(first),4)&":"&
ADDRESS(ROW(last),COLUMN(last),4)
)
Where rng is the generic placeholder for a named range or Excel Table. In this formula, the LET function is used to assign values to two variables: first and last. First represents the first cell in the range and last represents the last cell in the range. These values are assigned with the TAKE function like this:
first,TAKE(rng,1,1), // first cell (B5)
last,TAKE(rng,-1,-1), // last cell (E16)
The TAKE function returns a subset of a given array or range. The size of the array returned is determined by separate rows and columns arguments. When positive numbers are provided for rows or columns, TAKE returns values from the start or top of the array. Negative numbers take values from the end or bottom of the array. What’s tricky about this, and not obvious, is that when working with ranges, TAKE returns a valid reference. You don’t normally see the reference because as with most formulas, Excel returns the value at that reference, not the reference itself. However, the reference is there, as is obvious in the next step.
Finally, the ADDRESS function is used to generate an address for both the first cell and the last cell in the range, and the two results are concatenated with a colon (:) in between:
ADDRESS(ROW(first),COLUMN(first),4)&":"&ADDRESS(ROW(last),COLUMN(last),4)
Substituting the references returned by TAKE, the formula evaluates like this:
=ADDRESS(ROW(B5),COLUMN(B5),4)&":"&ADDRESS(ROW(E16),COLUMN(E16),4)
=ADDRESS(5,2,4)&":"&ADDRESS(16,4,4)
="B5"&":"&"E16"
="B5:E16"
Named range as text
To get an address for a named range entered as a text value (i.e. «range», «data», etc.), you’ll need to use the INDIRECT function to change the text into a valid reference before proceeding. For example, to get the address of a table name entered in A1 as text, you could use this unwieldy formula:
=ADDRESS(ROW(INDIRECT(A1)),COLUMN(INDIRECT(A1)))&":"&ADDRESS(ROW(INDIRECT(A1))+ROWS(INDIRECT(A1))-1,COLUMN(INDIRECT(A1))+COLUMNS(INDIRECT(A1))-1)
In the dynamic array version of Excel, the LET function makes this much simpler. With a range or table name as text in cell A1, you can call INDIRECT just once like this:
=LET(
rng,INDIRECT(A1),
first,TAKE(rng,1,1),
last,TAKE(rng,-1,-1),
ADDRESS(ROW(first),COLUMN(first),4)&":"&
ADDRESS(ROW(last),COLUMN(last),4)
)
You can read more about the LET function here.
Named LAMBDA option
Taking things a step further, you can use the LAMBDA function to create a custom function like this:
=LAMBDA(range,
LET(
rng,IF(ISREF(range),range,INDIRECT(range)),
first,TAKE(rng,1,1),
last,TAKE(rng,-1,-1),
ADDRESS(ROW(first),COLUMN(first),4)&":"&
ADDRESS(ROW(last),COLUMN(last),4)
)
)(data)
This version of the formula does the same thing as the formula above with one additional step: it checks for range or table names entered as text values. This is done with the ISREF function in the first step. If the value passed in for range is a valid reference, we use it as-is to assign a value to rng. If not, we run it through the INDIRECT function to try and get a valid reference.
Finally, if we give the LAMBDA formula above the name «GetRange», we can call it on any valid range like this:
=GetRange(data)
Read more about creating and naming custom LAMBDA formulas here.
Check reference returned by formula
A nice feature of the LAMBDA version of the formula is we easily can use it to check the result of any formula that returns a range. For example, we can call it with the OFFSET function like this:
=GetRange(OFFSET(A1,4,1,10,2)) // returns "B5:C14"
The point here is that it is not easy to understand what range is returned by OFFSET, because Excel will return only the values in the range. The custom GetRange function makes it possible to print the range returned by a formula explicitly.
Other ideas
I looked at two other formulas to solve this problem. The first uses ADDRESS and TAKE:
=LET(
d,ADDRESS(ROW(data),COLUMN(data),4),
TAKE(a,1,1)&":"&TAKE(a,-1,-1)
)
The second uses ADDRESS and the new TOCOL function:
=LET(
d,TOCOL(ADDRESS(ROW(data),COLUMN(data),4)),
INDEX(d,1)&":"&INDEX(d,ROWS(d))
)
Both formulas use the ADDRESS function to spin up all of the addresses in the range at the same time. The first formula then uses the TAKE function to get the first and last address. The second formula uses the TOCOL function to unwrap the array of references created by ADDRESS, then it uses the INDEX function twice to get the first and the last value. On small ranges, these formulas should work nicely. However, on very large ranges you are likely to see a performance hit because of time needed to create all of the extra addresses. The proposes formula solution above avoids this problem by only creating the first and last reference. The tradeoff is that the formula is more complex.