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:
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».
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
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
Not all adjacent 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"
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).
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
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
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
After the 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
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
To hide rows:
Range("A1:C3").Rows.Hidden = True
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
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!
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
Excel VBA Columns Property
VBA Columns property is used to refer to columns in the worksheet. Using this property we can use any column in the specified worksheet and work with it.
When we want to refer to the cell, we use either the Range object or Cells property. Similarly, how do you refer to columns in VBA? We can refer to columns by using the “Columns” property. Look at the syntax of COLUMNS property.
Table of contents
- Excel VBA Columns Property
- Examples
- Example #1
- Example #2 – Select Column Based on Variable Value
- Example #3 – Select Column Based on Cell Value
- Example #4 – Combination of Range & Column Property
- Example #5 – Select Multiple Columns with Range Object
- Recommended Articles
- Examples
We need to mention the column number or header alphabet to reference the column.
For example, if we want to refer to the second column, we can write the code in three ways.
Columns (2)
Columns(“B:B”)
Range (“B:B”)
Examples
You can download this VBA Columns Excel Template here – VBA Columns Excel Template
Example #1
If you want to select the second column in the worksheet, then first, we need to mention the column number we need to select.
Code:
Sub Columns_Example() Columns (2) End Sub
Now, put a dot (.) to choose the “Select” method.
One of the problems with this property is we do not get to see the IntelliSense list of VBA.
Code:
Sub Columns_Example() Columns(2).Select End Sub
So, the above VBA codeVBA code refers to a set of instructions written by the user in the Visual Basic Applications programming language on a Visual Basic Editor (VBE) to perform a specific task.read more will select the second column of the worksheet.
Instead of mentioning the column number, we can use the column header alphabet “B” to select the second column.
Code:
Sub Columns_Example() Columns("B").Select Columns("B:B").Select End Sub
The above codes will select column B, i.e., the second column.
Example #2 – Select Column Based on Variable Value
We can also use the variable to select the column number. For example, look at the below code now.
Code:
Sub Columns_Example() Dim ColNum As Integer ColNum = 4 Columns(ColNum).Select End Sub
In the above, we have declared the variable as “Integer” and assigned the value of 4 to this variable.
We have supplied this variable instead of the column number for the Column’s property. Since the variable holds the value of 4, it will select the 4th column.
Example #3 – Select Column Based on Cell Value
We have seen how to select the column based on variable value now. Next, we will see how we can select the column based on the cell value number. For example, in cell A1 we have entered the number 3.
The code below will select the column based on the number in cell A1.
Code:
Sub Columns_Example() Dim ColNum As Integer ColNum = Range("A1").Value Columns(ColNum).Select End Sub
The above code is the same as the previous one. Still, the only thing we have changed here is instead of assigning the direct number to the variable. Instead, we gave a variable value as “whatever the number is in cell A1.”
Since we have a value of 3 in cell A1, it will select the third column.
Example #4 – Combination of Range & Column Property
We can also use the Columns property with the Range object. Using the Range object, we can specify the specific range. For example, look at the below code.
Code:
Sub Columns_Example1() Range("C1:D5").Columns(2).Select End Sub
In the above example, we have specified the range of cells as C1 to D5. Then, using the columns property, we have specified the column number as 2 to select.
Now, in general, our second column is B. So the code has to select the “B” column but see what happens when we run the code.
It has selected the cells from D1 to D5.
In our perception, it should have selected the second column, i.e., column B. But now, it has selected the cells from D1 to D5.
It has selected these cells because before using the COLUMNS property, we have specified the range using the RANGE object as C1 to D5. Now, the property thinks within this range as the columns and selects the second column in the range C1 to D5. Therefore, D is the second column, and specified cells are D1 to D5.
Example #5 – Select Multiple Columns with Range Object
Using the Range object and Columns property, we can select multiple columns. For example, look at the below code.
Code:
Sub Columns_Example1() Range(Columns(2), Columns(5)).Select End Sub
The code will select the column from the second column to the fifth column, i.e., from column B to E.
We can also write the code in this way.
Code:
Sub Columns_Example1() Range(Columns(B), Columns(E)).Select End Sub
The above is the same as the previous one and selects the columns from B to E.
Like this, we can use the COLUMNS property to work with the worksheet.
Recommended Articles
This article has been a guide to VBA Columns. Here, we discuss examples of the column property in Excel VBA and select multiple columns with the range object and downloadable Excel templates. Below are some useful articles related to VBA: –
- DateSerial Function in Excel VBA
- Hide Columns in VBA
- Insert Columns in VBA
- Delete Column in VBA
- VBA Variable Types
I’m looking for an alternative to this code
, but using numbers.
I want to select 5 columns, the start column is a variable, and then it selects 5 columns from this.
Columns("A:E").Select
How do I use integers
instead, to reference columns? Something like below?
For n = 1 to 5
Columns("n : n + 4") .select
do sth
next n
feetwet
3,1967 gold badges45 silver badges83 bronze badges
asked Sep 30, 2014 at 2:29
You can use resize like this:
For n = 1 To 5
Columns(n).Resize(, 5).Select
'~~> rest of your code
Next
In any Range Manipulation that you do, always keep at the back of your mind Resize and Offset property.
answered Sep 30, 2014 at 3:26
L42L42
19.3k11 gold badges43 silver badges68 bronze badges
2
Columns("A:E").Select
Can be directly replaced by
Columns(1).Resize(, 5).EntireColumn.Select
Where 1 can be replaced by a variable
n = 5
Columns(n).Resize(, n+4).EntireColumn.Select
In my opinion you are best dealing with a block of columns rather than looping through columns n to n + 4 as it is more efficient.
In addition, using select will slow your code down. So instead of selecting your columns and then performing an action on the selection try instead to perform the action directly. Below is an example to change the colour of columns A-E to yellow.
Columns(1).Resize(, 5).EntireColumn.Interior.Color = 65535
answered Feb 10, 2017 at 9:28
McPaddyMcPaddy
1841 silver badge9 bronze badges
you can use range
with cells
to get the effect you want (but it would be better not to use select if you don’t have to)
For n = 1 to 5
range(cells(1,n).entirecolumn,cells(1,n+4).entirecolumn).Select
do sth
next n
answered Sep 30, 2014 at 2:54
SeanCSeanC
15.6k5 gold badges45 silver badges65 bronze badges
Try using the following, where n
is your variable and x is your offset (4 in this case):
LEFT(ADDRESS(1,n+x,4),1)
This will return the letter of that column (so for n=1 and x=4, it’ll return A+4 = E). You can then use INDIRECT()
to reference this, as so:
COLUMNS(INDIRECT(LEFT(ADDRESS(1,n,4),1)&":"&LEFT(ADDRESS(1,n+x,4),1)))
which with n=1, x=4 becomes:
COLUMNS(INDIRECT("A"&":"&"E"))
and so:
COLUMNS(A:E)
answered Sep 30, 2014 at 2:58
In the example code below I use variables just to show how the command could be used for other situations.
FirstCol = 1
LastCol = FirstCol + 5
Range(Columns(FirstCol), Columns(LastCol)).Select
answered Mar 15, 2016 at 3:43
Dave FDave F
15114 bronze badges
0
no need for loops or such.. try this..
dim startColumnas integer
dim endColumn as integer
startColumn = 7
endColumn = 24
Range(Cells(, startColumn), Cells(, endColumn)).ColumnWidth = 3.8 ' <~~ whatever width you want to set..*
roadrunner66
7,6424 gold badges31 silver badges38 bronze badges
answered Apr 11, 2016 at 18:09
3
You can specify addresses as «R1C2» instead of «B2». Under File -> Options -> Formuals -> Workingg with Formulas there is a toggle R1C1 reference style. which can be set, as illustrated below.
answered Sep 30, 2014 at 2:46
Pieter GeerkensPieter Geerkens
11.7k2 gold badges31 silver badges52 bronze badges
I was looking for a similar thing.
My problem was to find the last column based on row 5 and then select 3 columns before including the last column.
Dim lColumn As Long
lColumn = ActiveSheet.Cells(5,Columns.Count).End(xlToLeft).Column
MsgBox ("The last used column is: " & lColumn)
Range(Columns(lColumn - 3), Columns(lColumn)).Select
Message box is optional as it is more of a control check. If you want to select the columns after the last column then you simply reverse the range selection
Dim lColumn As Long
lColumn = ActiveSheet.Cells(5,Columns.Count).End(xlToLeft).Column
MsgBox ("The last used column is: " & lColumn)
Range(Columns(lColumn), Columns(lColumn + 3)).Select
answered Jun 27, 2018 at 9:02
dapazdapaz
80310 silver badges16 bronze badges
In this way, you can start to select data even behind column «Z» and select a lot of columns.
Sub SelectColumNums()
Dim xCol1 As Integer, xNumOfCols as integer
xCol1 = 26
xNumOfCols = 17
Range(Columns(xCol1), Columns(xCol1 + xNumOfCols)).Select
End Sub
answered May 6, 2015 at 1:12
Excel VBA Columns Property
We all are well aware of the fact that an Excel Worksheet is arranged in columns and rows and each intersection of rows and columns is considered as a cell. Whenever we want to refer a cell in Excel through VBA, we can use the Range or Cells properties. What if we want to refer the columns from Excel worksheet? Is there any function which we can use to refer the same? The answer is a big YES!
Yes, there is a property in VBA called “Columns” which helps you in referring as well as returning the column from given Excel Worksheet. We can refer any column from the worksheet using this property and can manipulate the same.
Syntax of VBA Columns:
The syntax for VBA Columns property is as shown below:
Where,
- RowIndex – Represents the row number from which the cells have to be retrieved.
- ColumnIndex – Represents the column number which is in an intersection with the respective rows and cells.
Obviously, which column needs to be included/used for further proceedings is being used by these two arguments. Both are optional and if not provided by default would be considered as the first row and first column.
How to Use Columns Property in Excel VBA?
Below are the different examples to use columns property in excel using VBA code.
You can download this VBA Columns Excel Template here – VBA Columns Excel Template
Example #1 – Select Column using VBA Columns Property
We will see how a column can be selected from a worksheet using VBA Columns property. For this, follow the below steps:
Step 1: Insert a new module under Visual Basic Editor (VBE) where you can write the block of codes. Click on Insert tab and select Module in VBA pane.
Step 2: Define a new sub-procedure which can hold the macro you are about to write.
Code:
Sub Example_1() End Sub
Step 3: Use Columns.Select property from VBA to select the first column from your worksheet. This actually has different ways, you can use Columns(1).Select initially. See the screenshot below:
Code:
Sub Example_1() Columns(1).Select End Sub
The Columns property in this small piece of code specifies the column number and Select property allows the VBA to select the column. Therefore in this code, Column 1 is selected based on the given inputs.
Step 4: Hit F5 or click on the Run button to run this code and see the output. You can see that column 1 will be selected in your excel sheet.
This is one way to use columns property to select a column from a worksheet. We can also use the column names instead of column numbers in the code. Below code also gives the same result.
Code:
Sub Example_1() Columns("A").Select End Sub
Example #2 – VBA Columns as a Worksheet Function
If we are using the Columns property without any qualifier, then it will only work on all the Active worksheets present in a workbook. However, in order to make the code more secure, we can use the worksheet qualifier with columns and make our code more secure. Follow the steps below:
Step 1: Define a new sub-procedure which can hold the macro under the module.
Code:
Sub Example_2() End Sub
Now we are going to use Worksheets.Columns property to select a column from a specified worksheet.
Step 2: Start typing the Worksheets qualifier under given macro. This qualifier needs the name of the worksheet, specify the sheet name as “Example 2” (Don’t forget to add the parentheses). This will allow the system to access the worksheet named Example 2 from the current workbook.
Code:
Sub Example_2() Worksheets("Example 2") End Sub
Step 3: Now use Columns property which will allow you to perform different column operations on a selected worksheet. I will choose the 4th column. I either can choose it by writing the index as 4 or specifying the column alphabet which is “D”.
Code:
Sub Example_2() Worksheets("Example 2").Columns("D") End Sub
As of here, we have selected a worksheet named Example 2 and accessed the column D from it. Now, we need to perform some operations on the column accessed.
Step 4: Use Select property after Columns to select the column specified in the current worksheet.
Code:
Sub Example_2() Worksheets("Example 2").Columns("D").Select End Sub
Step 5: Run the code by pressing the F5 key or by clicking on Play Button.
Example #3 – VBA Columns Property to Select Range of Cells
Suppose we want to select the range of cells across different columns. We can combine the Range as well as Columns property to do so. Follow the steps below:
Suppose we have our data spread across B1 to D4 in the worksheet as shown below:
Step 1: Define a new sub-procedure to hold a macro.
Code:
Sub Example_3() End Sub
Step 2: Use the Worksheets qualifier to be able to access the worksheet named “Example 3” where we have the data shown in the above screenshot.
Code:
Sub Example_3() Worksheets("Example 3") End Sub
Step 3: Use Range property to set the range for this code from B1 to D4. Use the following code Range(“B1:D4”) for the same.
Code:
Sub Example_3() Worksheets("Example 3").Range("B1:D4") End Sub
Step 4: Use Columns property to access the second column from the selection. Use code as Columns(2) in order to access the second column from the accessed range.
Code:
Sub Example_3() Worksheets("Example 3").Range("B1:D4").Columns(2) End Sub
Step 5: Now, the most important part. We have accessed the worksheet, range, and column. However, in order to select the accessed content, we need to use Select property in VBA. See the screenshot below for the code layout.
Code:
Sub Example_3() Worksheets("Example 3").Range("B1:D4").Columns(2).Select End Sub
Step 6: Run this code by hitting F5 or Run button and see the output.
You can see the code has selected Column C from the excel worksheet though you have put the column value as 2 (which means the second column). The reason for this is, we have chosen the range as B1:D4 in this code. Which consists of three columns B, C, D. At the time of execution column B is considered as first column, C as second and D as the third column instead of their actual positionings. The range function has reduced the scope for this function for B1:D4 only.
Things to Remember
- We can’t see the IntelliSense list of properties when we are working on VBA Columns.
- This property is categorized under Worksheet property in VBA.
Recommended Articles
This is a guide to VBA Columns. Here we discuss how to use columns property in Excel by using VBA code along with practical examples and downloadable excel template. You can also go through our other suggested articles –
- VBA Insert Column
- Grouping Columns in Excel
- VBA Delete Column
- Switching Columns in Excel
This example teaches you how to select entire rows and columns in Excel VBA. Are you ready?
Place a command button on your worksheet and add the following code lines:
1. The following code line selects the entire sheet.
Cells.Select
Note: because we placed our command button on the first worksheet, this code line selects the entire first sheet. To select cells on another worksheet, you have to activate this sheet first. For example, the following code lines select the entire second worksheet.
Worksheets(2).Activate
Worksheets(2).Cells.Select
2. The following code line selects the second column.
Columns(2).Select
3. The following code line selects the seventh row.
Rows(7).Select
4. To select multiple rows, add a code line like this:
Rows(«5:7»).Select
5. To select multiple columns, add a code line like this:
Columns(«B:E»).Select
6. Be careful not to mix up the Rows and Columns properties with the Row and Column properties. The Rows and Columns properties return a Range object. The Row and Column properties return a single value.
Code line:
MsgBox Cells(5, 2).Row
Result:
7. Select cell D6. The following code line selects the entire row of the active cell.
ActiveCell.EntireRow.Select
Note: border for illustration only.
8. Select cell D6. The following code line enters the value 2 into the first cell of the column that contains the active cell.
ActiveCell.EntireColumn.Cells(1).Value = 2
Note: border for illustration only.
9. Select cell D6. The following code line enters the value 3 into the first cell of the row below the row that contains the active cell.
ActiveCell.EntireRow.Offset(1, 0).Cells(1).Value = 3
Note: border for illustration only.
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.
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")
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)
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.
In addition, they can combine data from other different sources (such as Jira, Mailchimp, etc.) into one destination for analysis purposes.
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
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
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:
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.
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.
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
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:
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:
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:
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.
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!
-
Senior analyst programmer
Back to Blog
Focus on your business
goals while we take care of your data!
Try Coupler.io