One of the basic things you need to do in Excel VBA is to select a specific range to do something with it. This article will show you how to use Range, Cells, Offset and Resize to select a range in Excel VBA.
Select all the cells of a worksheet
Cells.Select
Select a cell
Cells(4, 5).Select
=
Range("E4").Select
It seems Range() is much easier to read and Cells() is easier to use inside a loop.
Select a set of contiguous cells
Range("C3:G8").Select
=
Range(Cells(3, 3), Cells(8, 7)).Select
=
Range("C3", "G8").Select
Select a set of non contiguous cells
Range("A2,A4,B5").Select
Select a set of non contiguous cells and a range
Range("A2,A4,B5:B8").Select
Select a named range
Range("MyRange").Select
=
Application.Goto "MyRange"
Select an entire row
Range("1:1").Select
Select an entire column
Range("A:A").Select
Select the last cell of a column of contiguous data
Range("A1").End(xlDown).Select
When this code is used with the following example table, cell A3 will be selected.
Select the blank cell at bottom of a column of contiguous data
Range("A1").End(xlDown).Offset(1,0).Select
When this code is used with the following example table, cell A4 will be selected.
Select an entire range of contiguous cells in a column
Range("A1", Range("A1").End(xlDown)).Select
When this code is used with the following example table, range A1:A3 will be selected.
Select an entire range of non-contiguous cells in a column
Range("A1", Range("A" & Rows.Count).End(xlUp)).Select
Note: This VBA code supports Excel 2003 to 2013.
When this code is used with the following example table, range A1:A8 will be selected.
Select a rectangular range of cells around a cell
Range("A1").CurrentRegion.Select
Select a cell relative to another cell
ActiveCell.Offset(5, 5).Select
Range("D3").Offset(5, -1).Select
Select a specified range, offset It, and then resize It
Range("A1").Offset(3, 2).Resize(3, 3).Select
When this code is used with the following example table, range C4:E6 will be selected.
Key Notes
- You can use the Range property as well as Cells property to use the Select property to select a range.
Select a Single Cell
To select a single cell, you need to define the cell address using the range, and then you need to use the select property. Let’s say if you want to select cell A1, the code would be:
Range("A1").Select
And if you want to use the CELLS, in that case, the code would be:
Cells(1,1).Select
Select a Range of Cells
To select an entire range, you need to define the address of the range and then use the select property. For example, if you want to select the range A1 to A10, the code would be:
Range("A1:A10").Select
Select Non-Continues Range
To select a non-continuous range, you need to use a comma within the cell or range addresses, and then use the select the property. Let’s say if you want to select the range A1 to A10 and C5 to C10, the code would be:
Range("A1:A10, C5:C10").Select
And if you want to select single cells that are non-continuous, the code would be:
Range("A1, A5, A9").Select
Select a Column
To select a column, let’s say column A, you need to write code like the following:
Range("A:A").Select
And if you want to select multiple columns, in that case, the code would be like the following:
Range("A:C").Select
Range("A:A, C:C").Select
Select a Row
In the same way, if you want to select a row, let’s say row five, the code would be like the following.
Range("5:5").Select
And for multiple rows, the code would be:
Range("1:5").Select
Range("1:1, 3:3").Select
Select All the Cells of a Worksheet
Let’s say you want to select all the cells in the worksheet, just like you use the keyboard shortcut Control +A. You need to use the following code.
ActiveSheet.Cells.Select
Cells.Select
“Cells” refer to all the cells in the worksheet, and then select property selects them.
Select Cells with Data Only
Here “Cells with Data” only mean a section in the worksheet where cells have data and you can use the following code.
ActiveSheet.UsedRange.Select
Select a Named Range
If you have a named range, you can select it by using its name.
Range("my_range").Select
In the above code, you have the “my_range” named range and then the select property, and when you run this macro, it selects the specified range.
Select an Excel Table
If you work with Excel tables, you can also select them using the select property. Let’s say you have a table with the name “Data”, then the code to select that table would be:
If you want to select a column instead of the entire table, then the code would be, like the following:
Range("Data[Amount]").Select
And if you want to select the entire column including the header, then the code you can use:
Range("Data[[#All],[Amount]]").Select
You can also use the OFFSET property to select a cell or a range by navigating from a cell or a range. Let’s suppose you want to select a cell that is four columns right and five rows down from the A1; you can use the following code.
Range("A1").Offset(5, 4).Select
More Tutorials
- Count Rows using VBA in Excel
- Excel VBA Font (Color, Size, Type, and Bold)
- Excel VBA Hide and Unhide a Column or a Row
- Excel VBA Range – Working with Range and Cells in VBA
- Apply Borders on a Cell using VBA in Excel
- Find Last Row, Column, and Cell using VBA in Excel
- Insert a Row using VBA in Excel
- Merge Cells in Excel using a VBA Code
- SELECT ALL the Cells in a Worksheet using a VBA Code
- ActiveCell in VBA in Excel
- Special Cells Method in VBA in Excel
- UsedRange Property in VBA in Excel
- VBA AutoFit (Rows, Column, or the Entire Worksheet)
- VBA ClearContents (from a Cell, Range, or Entire Worksheet)
- VBA Copy Range to Another Sheet + Workbook
- VBA Enter Value in a Cell (Set, Get and Change)
- VBA Insert Column (Single and Multiple)
- VBA Named Range | (Static + from Selection + Dynamic)
- VBA Range Offset
- VBA Sort Range | (Descending, Multiple Columns, Sort Orientation
- VBA Wrap Text (Cell, Range, and Entire Worksheet)
- VBA Check IF a Cell is Empty + Multiple Cells
⇠ Back to What is VBA in Excel
Helpful Links – Developer Tab – Visual Basic Editor – Run a Macro – Personal Macro Workbook – Excel Macro Recorder – VBA Interview Questions – VBA Codes
In this Article
- Select a Single Cell Using VBA
- Select a Range of Cells Using VBA
- Select a Range of Non-Contiguous Cells Using VBA
- Select All the Cells in a Worksheet
- Select a Row
- Select a Column
- Select the Last Non-Blank Cell in a Column
- Select the Last Non-Blank Cell in a Row
- Select the Current Region in VBA
- Select a Cell That is Relative To Another Cell
- Select a Named Range in Excel
- Selecting a Cell on Another Worksheet
- Manipulating the Selection Object in VBA
- Using the With…End With Construct
VBA allows you to select a cell, ranges of cells, or all the cells in the worksheet. You can manipulate the selected cell or range using the Selection Object.
Select a Single Cell Using VBA
You can select a cell in a worksheet using the Select method. The following code will select cell A2 in the ActiveWorksheet:
Range("A2").Select
Or
Cells(2, 1).Select
The result is:
Select a Range of Cells Using VBA
You can select a group of cells in a worksheet using the Select method and the Range object. The following code will select A1:C5:
Range("A1:C5").Select
Select a Range of Non-Contiguous Cells Using VBA
You can select cells or ranges that are not next to each other, by separating the cells or ranges using a comma in VBA. The following code will allow you to select cells A1, C1, and E1:
Range("A1, C1, E1").Select
You can also select sets of non-contiguous ranges in VBA. The following code will select A1:A9 and B11:B18:
Range("A1:A9, B11:B18").Select
Select All the Cells in a Worksheet
You can select all the cells in a worksheet using VBA. The following code will select all the cells in a worksheet.
Cells.Select
Select a Row
You can select a certain row in a worksheet using the Row object and the index number of the row you want to select. The following code will select the first row in your worksheet:
Rows(1).Select
Select a Column
You can select a certain column in a worksheet using the Column object and the index number of the column you want to select. The following code will select column C in your worksheet:
Columns(3).Select
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
Select the Last Non-Blank Cell in a Column
Let’s say you have data in cells A1, A2, A3 and A4 and you would like to select the last non-blank cell which would be cell A4 in the column. You can use VBA to do this and the Range.End method.
The Range.End Method can take four arguments namely: xlToLeft, xlToRight, xlUp and xlDown.
The following code will select the last non-blank cell which would be A4 in this case, if A1 is the active cell:
Range("A1").End(xlDown).Select
Select the Last Non-Blank Cell in a Row
Let’s say you have data in cells A1, B1, C1, D1, and E1 and you would like to select the last non-blank cell which would be cell E1 in the row. You can use VBA to do this and the Range.End method.
The following code will select the last non-blank cell which would be E1 in this case, if A1 is the active cell:
Range("A1").End(xlToRight).Select
Select the Current Region in VBA
You can use the CurrentRegion Property of the Range Object in order to select a rectangular range of blank and non-blank cells around a specific given input cell. If you have data in cell A1, B1 and C1, the following code would select this region around cell A1:
Range("A1").CurrentRegion.Select
So the range A1:C1 would be selected.
VBA Programming | Code Generator does work for you!
Select a Cell That is Relative To Another Cell
You can use the Offset Property to select a cell that is relative to another cell. The following code shows you how to select cell B2 which is 1 row and 1 column relative to cell A1:
Range("A1").Offset(1, 1).Select
Select a Named Range in Excel
You can select Named Ranges as well. Let’s say you have named cells A1:A4 Fruit. You can use the following code to select this named range:
Range("Fruit").Select
Selecting a Cell on Another Worksheet
In order to select a cell on another worksheet, you first need to activate the sheet using the Worksheets.Activate method. The following code will allow you to select cell A7, on the sheet named Sheet5:
Worksheets("Sheet5").Activate
Range("A1").Select
Manipulating the Selection Object in VBA
Once you have selected a cell or range of cells, you can refer to the Selection Object in order to manipulate these cells. The following code selects the cells A1:C1 and sets the font of these cells to Arial, the font weight to bold, the font style to italics and the fill color to green.
Sub FormatSelection()
Range("A1:C1").Select
Selection.Font.Name = "Arial"
Selection.Font.Bold = True
Selection.Font.Italic = True
Selection.Interior.Color = vbGreen
End Sub
The result is:
Using the With…End With Construct
We can repeat the above example using the With / End With Statement to refer to the Selection Object only once. This saves typing and usually makes your code easier to read.
Sub UsingWithEndWithSelection()
Range("A1:C1").Select
With Selection
.Font.Name = "Arial"
.Font.Bold = True
.Font.Italic = True
.Interior.Color = vbGreen
End With
End Sub
When working with Excel, most of your time is spent in the worksheet area – dealing with cells and ranges.
And if you want to automate your work in Excel using VBA, you need to know how to work with cells and ranges using VBA.
There are a lot of different things you can do with ranges in VBA (such as select, copy, move, edit, etc.).
So to cover this topic, I will break this tutorial into sections and show you how to work with cells and ranges in Excel VBA using examples.
Let’s get started.
All the codes I mention in this tutorial need to be placed in the VB Editor. Go to the ‘Where to Put the VBA Code‘ section to know how it works.
If you’re interested in learning VBA the easy way, check out my Online Excel VBA Training.
Selecting a Cell / Range in Excel using VBA
To work with cells and ranges in Excel using VBA, you don’t need to select it.
In most of the cases, you are better off not selecting cells or ranges (as we will see).
Despite that, it’s important you go through this section and understand how it works. This will be crucial in your VBA learning and a lot of concepts covered here will be used throughout this tutorial.
So let’s start with a very simple example.
Selecting a Single Cell Using VBA
If you want to select a single cell in the active sheet (say A1), then you can use the below code:
Sub SelectCell() Range("A1").Select End Sub
The above code has the mandatory ‘Sub’ and ‘End Sub’ part, and a line of code that selects cell A1.
Range(“A1”) tells VBA the address of the cell that we want to refer to.
Select is a method of the Range object and selects the cells/range specified in the Range object. The cell references need to be enclosed in double quotes.
This code would show an error in case a chart sheet is an active sheet. A chart sheet contains charts and is not widely used. Since it doesn’t have cells/ranges in it, the above code can’t select it and would end up showing an error.
Note that since you want to select the cell in the active sheet, you just need to specify the cell address.
But if you want to select the cell in another sheet (let’s say Sheet2), you need to first activate Sheet2 and then select the cell in it.
Sub SelectCell() Worksheets("Sheet2").Activate Range("A1").Select End Sub
Similarly, you can also activate a workbook, then activate a specific worksheet in it, and then select a cell.
Sub SelectCell() Workbooks("Book2.xlsx").Worksheets("Sheet2").Activate Range("A1").Select End Sub
Note that when you refer to workbooks, you need to use the full name along with the file extension (.xlsx in the above code). In case the workbook has never been saved, you don’t need to use the file extension.
Now, these examples are not very useful, but you will see later in this tutorial how we can use the same concepts to copy and paste cells in Excel (using VBA).
Just as we select a cell, we can also select a range.
In case of a range, it could be a fixed size range or a variable size range.
In a fixed size range, you would know how big the range is and you can use the exact size in your VBA code. But with a variable-sized range, you have no idea how big the range is and you need to use a little bit of VBA magic.
Let’s see how to do this.
Selecting a Fix Sized Range
Here is the code that will select the range A1:D20.
Sub SelectRange() Range("A1:D20").Select End Sub
Another way of doing this is using the below code:
Sub SelectRange() Range("A1", "D20").Select End Sub
The above code takes the top-left cell address (A1) and the bottom-right cell address (D20) and selects the entire range. This technique becomes useful when you’re working with variably sized ranges (as we will see when the End property is covered later in this tutorial).
If you want the selection to happen in a different workbook or a different worksheet, then you need to tell VBA the exact names of these objects.
For example, the below code would select the range A1:D20 in Sheet2 worksheet in the Book2 workbook.
Sub SelectRange() Workbooks("Book2.xlsx").Worksheets("Sheet1").Activate Range("A1:D20").Select End Sub
Now, what if you don’t know how many rows are there. What if you want to select all the cells that have a value in it.
In these cases, you need to use the methods shown in the next section (on selecting variably sized range).
Selecting a Variably Sized Range
There are different ways you can select a range of cells. The method you choose would depend on how the data is structured.
In this section, I will cover some useful techniques that are really useful when you work with ranges in VBA.
Select Using CurrentRange Property
In cases where you don’t know how many rows/columns have the data, you can use the CurrentRange property of the Range object.
The CurrentRange property covers all the contiguous filled cells in a data range.
Below is the code that will select the current region that holds cell A1.
Sub SelectCurrentRegion() Range("A1").CurrentRegion.Select End Sub
The above method is good when you have all data as a table without any blank rows/columns in it.
But in case you have blank rows/columns in your data, it will not select the ones after the blank rows/columns. In the image below, the CurrentRegion code selects data till row 10 as row 11 is blank.
In such cases, you may want to use the UsedRange property of the Worksheet Object.
Select Using UsedRange Property
UsedRange allows you to refer to any cells that have been changed.
So the below code would select all the used cells in the active sheet.
Sub SelectUsedRegion() ActiveSheet.UsedRange.Select End Sub
Note that in case you have a far-off cell that has been used, it would be considered by the above code and all the cells till that used cell would be selected.
Select Using the End Property
Now, this part is really useful.
The End property allows you to select the last filled cell. This allows you to mimic the effect of Control Down/Up arrow key or Control Right/Left keys.
Let’s try and understand this using an example.
Suppose you have a dataset as shown below and you want to quickly select the last filled cells in column A.
The problem here is that data can change and you don’t know how many cells are filled. If you have to do this using keyboard, you can select cell A1, and then use Control + Down arrow key, and it will select the last filled cell in the column.
Now let’s see how to do this using VBA. This technique comes in handy when you want to quickly jump to the last filled cell in a variably-sized column
Sub GoToLastFilledCell() Range("A1").End(xlDown).Select End Sub
The above code would jump to the last filled cell in column A.
Similarly, you can use the End(xlToRight) to jump to the last filled cell in a row.
Sub GoToLastFilledCell() Range("A1").End(xlToRight).Select End Sub
Now, what if you want to select the entire column instead of jumping to the last filled cell.
You can do that using the code below:
Sub SelectFilledCells() Range("A1", Range("A1").End(xlDown)).Select End Sub
In the above code, we have used the first and the last reference of the cell that we need to select. No matter how many filled cells are there, the above code will select all.
Remember the example above where we selected the range A1:D20 by using the following line of code:
Range(“A1″,”D20”)
Here A1 was the top-left cell and D20 was the bottom-right cell in the range. We can use the same logic in selecting variably sized ranges. But since we don’t know the exact address of the bottom-right cell, we used the End property to get it.
In Range(“A1”, Range(“A1”).End(xlDown)), “A1” refers to the first cell and Range(“A1”).End(xlDown) refers to the last cell. Since we have provided both the references, the Select method selects all the cells between these two references.
Similarly, you can also select an entire data set that has multiple rows and columns.
The below code would select all the filled rows/columns starting from cell A1.
Sub SelectFilledCells() Range("A1", Range("A1").End(xlDown).End(xlToRight)).Select End Sub
In the above code, we have used Range(“A1”).End(xlDown).End(xlToRight) to get the reference of the bottom-right filled cell of the dataset.
Difference between Using CurrentRegion and End
If you’re wondering why use the End property to select the filled range when we have the CurrentRegion property, let me tell you the difference.
With End property, you can specify the start cell. For example, if you have your data in A1:D20, but the first row are headers, you can use the End property to select the data without the headers (using the code below).
Sub SelectFilledCells() Range("A2", Range("A2").End(xlDown).End(xlToRight)).Select End Sub
But the CurrentRegion would automatically select the entire dataset, including the headers.
So far in this tutorial, we have seen how to refer to a range of cells using different ways.
Now let’s see some ways where we can actually use these techniques to get some work done.
Copy Cells / Ranges Using VBA
As I mentioned at the beginning of this tutorial, selecting a cell is not necessary to perform actions on it. You will see in this section how to copy cells and ranges without even selecting these.
Let’s start with a simple example.
Copying Single Cell
If you want to copy cell A1 and paste it into cell D1, the below code would do it.
Sub CopyCell() Range("A1").Copy Range("D1") End Sub
Note that the copy method of the range object copies the cell (just like Control +C) and pastes it in the specified destination.
In the above example code, the destination is specified in the same line where you use the Copy method. If you want to make your code even more readable, you can use the below code:
Sub CopyCell() Range("A1").Copy Destination:=Range("D1") End Sub
The above codes will copy and paste the value as well as formatting/formulas in it.
As you might have already noticed, the above code copies the cell without selecting it. No matter where you’re on the worksheet, the code will copy cell A1 and paste it on D1.
Also, note that the above code would overwrite any existing code in cell D2. If you want Excel to let you know if there is already something in cell D1 without overwriting it, you can use the code below.
Sub CopyCell() If Range("D1") <> "" Then Response = MsgBox("Do you want to overwrite the existing data", vbYesNo) End If If Response = vbYes Then Range("A1").Copy Range("D1") End If End Sub
Copying a Fix Sized Range
If you want to copy A1:D20 in J1:M20, you can use the below code:
Sub CopyRange() Range("A1:D20").Copy Range("J1") End Sub
In the destination cell, you just need to specify the address of the top-left cell. The code would automatically copy the exact copied range into the destination.
You can use the same construct to copy data from one sheet to the other.
The below code would copy A1:D20 from the active sheet to Sheet2.
Sub CopyRange() Range("A1:D20").Copy Worksheets("Sheet2").Range("A1") End Sub
The above copies the data from the active sheet. So make sure the sheet that has the data is the active sheet before running the code. To be safe, you can also specify the worksheet’s name while copying the data.
Sub CopyRange() Worksheets("Sheet1").Range("A1:D20").Copy Worksheets("Sheet2").Range("A1") End Sub
The good thing about the above code is that no matter which sheet is active, it will always copy the data from Sheet1 and paste it in Sheet2.
You can also copy a named range by using its name instead of the reference.
For example, if you have a named range called ‘SalesData’, you can use the below code to copy this data to Sheet2.
Sub CopyRange() Range("SalesData").Copy Worksheets("Sheet2").Range("A1") End Sub
If the scope of the named range is the entire workbook, you don’t need to be on the sheet that has the named range to run this code. Since the named range is scoped for the workbook, you can access it from any sheet using this code.
If you have a table with the name Table1, you can use the below code to copy it to Sheet2.
Sub CopyTable() Range("Table1[#All]").Copy Worksheets("Sheet2").Range("A1") End Sub
You can also copy a range to another Workbook.
In the following example, I copy the Excel table (Table1), into the Book2 workbook.
Sub CopyCurrentRegion() Range("Table1[#All]").Copy Workbooks("Book2.xlsx").Worksheets("Sheet1").Range("A1") End Sub
This code would work only if the Workbook is already open.
Copying a Variable Sized Range
One way to copy variable sized ranges is to convert these into named ranges or Excel Table and the use the codes as shown in the previous section.
But if you can’t do that, you can use the CurrentRegion or the End property of the range object.
The below code would copy the current region in the active sheet and paste it in Sheet2.
Sub CopyCurrentRegion() Range("A1").CurrentRegion.Copy Worksheets("Sheet2").Range("A1") End Sub
If you want to copy the first column of your data set till the last filled cell and paste it in Sheet2, you can use the below code:
Sub CopyCurrentRegion() Range("A1", Range("A1").End(xlDown)).Copy Worksheets("Sheet2").Range("A1") End Sub
If you want to copy the rows as well as columns, you can use the below code:
Sub CopyCurrentRegion() Range("A1", Range("A1").End(xlDown).End(xlToRight)).Copy Worksheets("Sheet2").Range("A1") End Sub
Note that all these codes don’t select the cells while getting executed. In general, you will find only a handful of cases where you actually need to select a cell/range before working on it.
Assigning Ranges to Object Variables
So far, we have been using the full address of the cells (such as Workbooks(“Book2.xlsx”).Worksheets(“Sheet1”).Range(“A1”)).
To make your code more manageable, you can assign these ranges to object variables and then use those variables.
For example, in the below code, I have assigned the source and destination range to object variables and then used these variables to copy data from one range to the other.
Sub CopyRange() Dim SourceRange As Range Dim DestinationRange As Range Set SourceRange = Worksheets("Sheet1").Range("A1:D20") Set DestinationRange = Worksheets("Sheet2").Range("A1") SourceRange.Copy DestinationRange End Sub
We start by declaring the variables as Range objects. Then we assign the range to these variables using the Set statement. Once the range has been assigned to the variable, you can simply use the variable.
Enter Data in the Next Empty Cell (Using Input Box)
You can use the Input boxes to allow the user to enter the data.
For example, suppose you have the data set below and you want to enter the sales record, you can use the input box in VBA. Using a code, we can make sure that it fills the data in the next blank row.
Sub EnterData() Dim RefRange As Range Set RefRange = Range("A1").End(xlDown).Offset(1, 0) Set ProductCategory = RefRange.Offset(0, 1) Set Quantity = RefRange.Offset(0, 2) Set Amount = RefRange.Offset(0, 3) RefRange.Value = RefRange.Offset(-1, 0).Value + 1 ProductCategory.Value = InputBox("Product Category") Quantity.Value = InputBox("Quantity") Amount.Value = InputBox("Amount") End Sub
The above code uses the VBA Input box to get the inputs from the user, and then enters the inputs into the specified cells.
Note that we didn’t use exact cell references. Instead, we have used the End and Offset property to find the last empty cell and fill the data in it.
This code is far from usable. For example, if you enter a text string when the input box asks for quantity or amount, you will notice that Excel allows it. You can use an If condition to check whether the value is numeric or not and then allow it accordingly.
Looping Through Cells / Ranges
So far we can have seen how to select, copy, and enter the data in cells and ranges.
In this section, we will see how to loop through a set of cells/rows/columns in a range. This could be useful when you want to analyze each cell and perform some action based on it.
For example, if you want to highlight every third row in the selection, then you need to loop through and check for the row number. Similarly, if you want to highlight all the negative cells by changing the font color to red, you need to loop through and analyze each cell’s value.
Here is the code that will loop through the rows in the selected cells and highlight alternate rows.
Sub HighlightAlternateRows() Dim Myrange As Range Dim Myrow As Range Set Myrange = Selection For Each Myrow In Myrange.Rows If Myrow.Row Mod 2 = 0 Then Myrow.Interior.Color = vbCyan End If Next Myrow End Sub
The above code uses the MOD function to check the row number in the selection. If the row number is even, it gets highlighted in cyan color.
Here is another example where the code goes through each cell and highlights the cells that have a negative value in it.
Sub HighlightAlternateRows() Dim Myrange As Range Dim Mycell As Range Set Myrange = Selection For Each Mycell In Myrange If Mycell < 0 Then Mycell.Interior.Color = vbRed End If Next Mycell End Sub
Note that you can do the same thing using Conditional Formatting (which is dynamic and a better way to do this). This example is only for the purpose of showing you how looping works with cells and ranges in VBA.
Where to Put the VBA Code
Wondering where the VBA code goes in your Excel workbook?
Excel has a VBA backend called the VBA editor. You need to copy and paste the code in the VB Editor module code window.
Here are the steps to do this:
- Go to the Developer tab.
- Click on the Visual Basic option. This will open the VB editor in the backend.
- In the Project Explorer pane in the VB Editor, right-click on any object for the workbook in which you want to insert the code. If you don’t see the Project Explorer, go to the View tab and click on Project Explorer.
- Go to Insert and click on Module. This will insert a module object for your workbook.
- Copy and paste the code in the module window.
You May Also Like the Following Excel Tutorials:
- Working with Worksheets using VBA.
- Working with Workbooks using VBA.
- Creating User-Defined Functions in Excel.
- For Next Loop in Excel VBA – A Beginner’s Guide with Examples.
- How to Use Excel VBA InStr Function (with practical EXAMPLES).
- Excel VBA Msgbox.
- How to Record a Macro in Excel.
- How to Run a Macro in Excel.
- How to Create an Add-in in Excel.
- Excel Personal Macro Workbook | Save & Use Macros in All Workbooks.
- Excel VBA Events – An Easy (and Complete) Guide.
- Excel VBA Error Handling.
- How to Sort Data in Excel using VBA (A Step-by-Step Guide).
- 24 Useful Excel Macro Examples for VBA Beginners (Ready-to-use).
Selecting multiple ranges in Excel VBA helps your code to work faster. You can select multiple ranges in single line code and perform the action you want to perform.
Normally we code a range by writing it within «» as under
Range("A1:A10").Select
However if you put , between multiple ranges within the same line of the code you can select multiple ranges as given under
Range("A1:A10,D1:D10,F1:F10").Select
How to use Multiple Ranges in Excel VBA
Following macro code will explain you how to use multiple ranges in Excel VBA
Sub Multiple_ranges()
Range("A1:A10").Select
MsgBox ("Single Range Selected")
Range("A1:A10,D1:D10,F1:F10").Select
MsgBox ("Multiple Ranges Selected")
Selection.Copy
Range("A11").Select
ActiveSheet.Paste
End Sub
In the above macro we have selected range three different ranges
A1:A10
D1:D10
F1:F10
After selection we have copied the contents to Range A11. Another option for doing this was to copy the contents one by one for each of the range. However copy and paste is only one of the example you can use this for any desired action by you.
You can combine multiple ranges into one Range object using the Union method.
The following example creates a Range object called myMultipleRange, defines it as the ranges A1:B2 and C3:D4, and then formats the combined ranges as bold.
Sub MultipleRange()
Dim r1, r2, myMultipleRange As Range
Set r1 = Sheets("Sheet1").Range("A1:B2")
Set r2 = Sheets("Sheet1").Range("C3:D4")
Set myMultipleRange = Union(r1, r2)
myMultipleRange.Font.Bold = True
End Sub
I found a similar solution to this question in c# How to Select all the cells in a worksheet in Excel.Range object of c#?
What is the process to do this in VBA?
I select data normally by using «ctrl+shift over arrow, down arrow» to select an entire range of cells. When I run this in a macro it codes out A1:Q398247930, for example. I need it to just be
.SetRange Range("A1:whenever I run out of rows and columns")
I could easily do it myself without a macro, but I’m trying to make the entire process a macro, and this is just a piece of it.
Sub sort()
'sort Macro
Range("B2").Select
ActiveWorkbook.Worksheets("Master").sort.SortFields.Clear
ActiveWorkbook.Worksheets("Master").sort.SortFields.Add Key:=Range("B2"), _
SortOn:=xlSortOnValues, Order:=xlAscending, DataOption:=xlSortNormal
With ActiveWorkbook.Worksheets("Master").sort
.SetRange Range("A1:whenever I run out of rows and columns")
.Header = xlNo
.MatchCase = False
.Orientation = xlTopToBottom
.SortMethod = xlPinYin
.Apply
End With
End Sub
edit:
There are other parts where I might want to use the same code but the range is say «C3:End of rows & columns». Is there a way in VBA to get the location of the last cell in the document?
asked Jul 30, 2013 at 18:50
C. TewaltC. Tewalt
2,2612 gold badges29 silver badges47 bronze badges
I believe you want to find the current region of A1 and surrounding cells — not necessarily all cells on the sheet.
If so — simply use…
Range(«A1»).CurrentRegion
answered Jul 30, 2013 at 19:17
ExcelExpertExcelExpert
3522 silver badges4 bronze badges
1
You can simply use cells.select
to select all cells in the worksheet. You can get a valid address by saying Range(Cells.Address)
.
If you want to find the last Used Range
where you have made some formatting change or entered a value into you can call ActiveSheet.UsedRange
and select it from there. Hope that helps.
June7
19.5k8 gold badges24 silver badges33 bronze badges
answered Jul 30, 2013 at 19:11
chanceachancea
5,8083 gold badges28 silver badges39 bronze badges
2
you can use all cells as a object like this :
Dim x as Range
Set x = Worksheets("Sheet name").Cells
X is now a range object that contains the entire worksheet
answered Apr 15, 2015 at 11:47
you have a few options here:
- Using the UsedRange property
- find the last row and column used
- use a mimic of shift down and shift right
I personally use the Used Range and find last row and column method most of the time.
Here’s how you would do it using the UsedRange property:
Sheets("Sheet_Name").UsedRange.Select
This statement will select all used ranges in the worksheet, note that sometimes this doesn’t work very well when you delete columns and rows.
The alternative is to find the very last cell used in the worksheet
Dim rngTemp As Range
Set rngTemp = Cells.Find("*", SearchOrder:=xlByRows, SearchDirection:=xlPrevious)
If Not rngTemp Is Nothing Then
Range(Cells(1, 1), rngTemp).Select
End If
What this code is doing:
- Find the last cell containing any value
- select cell(1,1) all the way to the last cell
answered Jul 30, 2013 at 20:32
Derek ChengDerek Cheng
5353 silver badges8 bronze badges
3
Another way to select all cells within a range, as long as the data is contiguous, is to use Range("A1", Range("A1").End(xlDown).End(xlToRight)).Select
.
answered Mar 29, 2019 at 19:38
I would recommend recording a macro, like found in this post;
Excel VBA macro to filter records
But if you are looking to find the end of your data and not the end of the workbook necessary, if there are not empty cells between the beginning and end of your data, I often use something like this;
R = 1
Do While Not IsEmpty(Sheets("Sheet1").Cells(R, 1))
R = R + 1
Loop
Range("A5:A" & R).Select 'This will give you a specific selection
You are left with R = to the number of the row after your data ends. This could be used for the column as well, and then you could use something like Cells(C , R).Select, if you made C the column representation.
answered Jul 30, 2013 at 19:25
MakeCentsMakeCents
7321 gold badge5 silver badges15 bronze badges
2
Sub SelectAllCellsInSheet(SheetName As String)
lastCol = Sheets(SheetName).Range("a1").End(xlToRight).Column
Lastrow = Sheets(SheetName).Cells(1, 1).End(xlDown).Row
Sheets(SheetName).Range("A1", Sheets(SheetName).Cells(Lastrow, lastCol)).Select
End Sub
To use with ActiveSheet:
Call SelectAllCellsInSheet(ActiveSheet.Name)
answered Mar 14, 2017 at 20:57
Yehia AmerYehia Amer
5985 silver badges11 bronze badges
Here is what I used, I know it could use some perfecting, but I think it will help others…
''STYLING''
Dim sheet As Range
' Find Number of rows used
Dim Final As Variant
Final = Range("A1").End(xlDown).Row
' Find Last Column
Dim lCol As Long
lCol = Cells(1, Columns.Count).End(xlToLeft).Column
Set sheet = ActiveWorkbook.ActiveSheet.Range("A" & Final & "", Cells(1, lCol ))
With sheet
.Interior.ColorIndex = 1
End With
answered Mar 16, 2019 at 4:29
I have found that the Worksheet «.UsedRange» method is superior in many instances to solve this problem.
I struggled with a truncation issue that is a normal behaviour of the «.CurrentRegion» method. Using [ Worksheets(«Sheet1»).Range(«A1»).CurrentRegion ] does not yield the results I desired when the worksheet consists of one column with blanks in the rows (and the blanks are wanted). In this case, the «.CurrentRegion» will truncate at the first record. I implemented a work around but recently found an even better one; see code below that allows copying the whole set to another sheet or to identify the actual address (or just rows and columns):
Sub mytest_GetAllUsedCells_in_Worksheet()
Dim myRange
Set myRange = Worksheets("Sheet1").UsedRange
'Alternative code: set myRange = activesheet.UsedRange
'use msgbox or debug.print to show the address range and counts
MsgBox myRange.Address
MsgBox myRange.Columns.Count
MsgBox myRange.Rows.Count
'Copy the Range of data to another sheet
'Note: contains all the cells with that are non-empty
myRange.Copy (Worksheets("Sheet2").Range("A1"))
'Note: transfers all cells starting at "A1" location.
' You can transfer to another area of the 2nd sheet
' by using an alternate starting location like "C5".
End Sub
answered May 2, 2019 at 19:38
Maybe this might work:
Sh.Range(«A1», Sh.Range(«A» & Rows.Count).End(xlUp))
answered Oct 31, 2014 at 18:38
Refering to the very first question, I am looking into the same.
The result I get, recording a macro, is, starting by selecting cell A76:
Sub find_last_row()
Range("A76").Select
Range(Selection, Selection.End(xlDown)).Select
End Sub
answered Aug 7, 2015 at 12:40
Excel VBA Selecting Range
To select any kind of range in VBA we have a function called SELECT. It doesn’t mean that what type of cells we want to select in the Excel worksheet. But, If we want to use the range of cells or a combination of cells in VBA, then VBA Select is the function that would help us in selecting the range of cells we want. In actual, SELECT is an application in VBA which is used by applying it after we choose the range of cells to be select. Choosing the cells we want to select doesn’t mean that we are actually selecting it. We need to place SELECT after we fix the cells which we want to consider in our range. The good thing about Select is, it does not have any syntax to be followed.
How to Select a Range of Cells in Excel VBA?
We will learn how to select a range of cells in Excel by using the VBA Code. For this, follow the below steps:
You can download this VBA Selecting Range Excel Template here – VBA Selecting Range Excel Template
Example #1
To apply the SELECT application using VBA,
Step 1: Insert a new module inside Visual Basic Editor (VBE). Click on Insert tab > select Module.
Step 2: Write the subprocedure of VBA Selecting Range in the same name or in the different names which defines the operation we do.
Code:
Sub VBA_Range() End Sub
Step 3: Now suppose, if we want to select the range of cells from cell A1 to B10 then use RANGE and in inverted quotes put the cells under range.
Code:
Sub VBA_Range() Range("A1:B10") End Sub
Step 4: Now to select the required application, after a dot and select the application called SELECT as shown below.
Code:
Sub VBA_Range() Range("A1:B10").Select End Sub
Step 5: Now we will compile the code by pressing function key F8 and to run the code, click on the Play button located below the menu bar. We will see in the current worksheet, cells from A1 to B10 are selected or covered in the highlighted area.
Example #2
There is another way to select any random cell range we want. For this, we will use the same coding pattern that we saw in example-2. For this, follow the below steps:
Step 1: Write the subprocedure for VBA Selecting Range.
Code:
Sub VBA_Range2() End Sub
Step 2: Now in the Range function, we will put the random cells that we want to select in place of sequential range. Let’s put cell A1, B2 and C3 separated by commas into the brackets.
Code:
Sub VBA_Range2() Range("A1, B2, C3").Select End Sub
Step 3: Now if the run the code, we will see cell A1, B2 and C3 will now be selected with a highlighted portion as shown below.
Example #3
There is one more method to select the Range. Here we will be using define a variable for RANGE function first. For this, follow the below steps:
Step 1: Write the subprocedure for VBA Selection Range. And in that define a variable for RANGE.
Code:
Sub VBA_Range3() Dim SelectRNG As Range End Sub
Step 2: Then use SET with defined variable and use RANGE function along with the cells which we want to select.
Code:
Sub VBA_Range3() Dim SelectRNG As Range Set SelectRNG = Range("A1:B10") End Sub
Step 3: At last, use the SELECT application with a defined variable as shown below.
Code:
Sub VBA_Range3() Dim SelectRNG As Range Set SelectRNG = Range("A1:B10") SelectRNG.Select End Sub
Step 4: Now again compile the code if required and run. We will see the range of cells A1 to B10 will get selected with the highlighted region.
Example #4
There is also another simplest way to select the range. For this, follow the below steps:
Step 1: For this again open a module and write the subprocedure for VBA Selecting Range. Now we will be using the function call CELLS. CELLS function in VBA allows us to choose the cells we want to select.
Code:
Sub VBA_Range4() End Sub
Step 2: Now put the cell numbers in the vertex of the X and Y positions. If we want to select the cell B3 then X would be 3 and Y would be 2 as shown below.
Code:
Sub VBA_Range4() Cells( End Sub
Step 3: Now use the SELECT application after the CELLS as shown below.
Code:
Sub VBA_Range4() Cells(3, 2).Select End Sub
Step 4: Now if we run the code, we will see, the cursor will be now placed to cell B3 as shown below.
Pros of VBA Selecting Range
- Shown examples have different but easiest ways to select the range.
- Selecting the range using directly RANGE function with SELECT is the best one-line code.
- We can select cells as a range in continuously or randomly.
Things to Remember
- To have a proper visual of range getting selected, put the cursor away from the range we want to select.
- If we choose the randomly distributed cells as Range, then some operation becomes limited to it. Such as, we cannot copy or cut the data in such a pattern manually.
- Processes shown for selecting the range in all the above examples are not limited to these. We can try the combination of all the different examples simultaneously we want.
- Once coding is done, save the Excel file in Macro Enabled Excel format which would help in retaining and saving the code multiple times.
Recommended Articles
This is a guide to the VBA Selecting Range. Here we discuss how to Select a Range of Cells in Excel VBA along with practical examples and downloadable excel template. You can also go through our other suggested articles –
- VBA Input
- VBA Login
- VBA Month
- VBA Login
О чём пойдёт речь?
Знакомство с объектной моделью Excel следует начинать с такого замечательного объекта, как Range. Поскольку любая ячейка — это Range, то без знания, как с этим объектом эффективно взаимодействовать, вам будет затруднительно программировать для Excel. Это очень ладно-скроенный объект. При некоторой сноровке вы найдёте его весьма удобным в эксплуатации.
Что такое объекты?
Мы собираемся изучать объект Range, поэтому пару слов надо сказать, что такое, собственно, «объект«. Всё, что вы наблюдаете в Excel, всё с чем вы работаете — это набор объектов. Например, лист рабочей книги Excel — не что иное, как объект типа WorkSheet. Однотипные объекты объединяют в коллекции себе подобных. Например, листы объединены в коллекцию Sheets. Чтобы не путать друг с другом объекты одного и того же типа, они имеют отличающиеся имена, а также номер индекса в коллекции. Объекты имеют свойства, методы и события.
Свойства — это информация об объекте. Часто эти свойства можно менять, что автоматически влечет изменения внешнего вида объекта или его поведения. Например свойство Visible объекта Worksheet отвечает за видимость листа на экране. Если ему присвоить значение xlSheetHidden (это константа, которая по факту равно нулю), то лист будет скрыт.
Методы — это то, что объект может делать. Например, метод Delete объекта Worksheet удаляет себя из книги. Метод Select делает лист активным.
События — это механизм, при помощи которого вы можете исполнять свой код VBA сразу по факту возникновения того или иного события с вашим объектом. Например, есть возможность выполнять ваш код, как только пользователь сделал текущим определенный лист рабочей книги, либо как только пользователь что-то изменил на этом листе.
Range это диапазон ячеек. Минимум — одна ячейка, максимум — весь лист, теоретически насчитывающий более 17 миллиардов ячеек (строки 2^20 * столбцы 2^14 = 2^34).
В Excel объявлены глобально и всегда готовы к использованию несколько коллекций, имеющий членами объекты типа Range, либо свойства это же типа.
Коллекции глобального объекта Application: Cells, Columns, Rows, а также свойства Range, Selection, ActiveCell, ThisCell.
ActiveCell — активная ячейка текущего листа, ThisCell — если вы написали пользовательскую функцию рабочего листа, то через это свойство вы можете определить какая конкретно ячейка в данный момент пересчитывает вашу функцию. Об остальных перечисленных объектов речь пойдёт ниже.
Работа с отдельными ячейками
Синтаксическая форма | Комментарии по использованию |
Range(«D5«) или [D5] |
Ячейка D5 текущего листа. Полная и краткая формы. Тут применим только синтаксис типа A1, но не R1C1. То есть такая конструкция Range(«R1C2«) — вызовет ошибку, даже если в книге Excel включен режим формул R1C1. Разумеется после этой формы вы можете обратиться к свойствам соответствующей ячейки. Например, Range(«D5«).Interior.Color = RGB(0, 255, 0). |
Cells(5, 4) или Cells(5, «D») | Ячейка D5 текущего листа через свойство Cells. 5 — строка (row), 4 — столбец (column). Допустимость второй формы мало кому известна. |
Cells(65540) | Ячейку D5 можно адресовать и через указание только одного параметра свойсва Cells. При этом нумерация идёт слева направо, потом сверху вниз. То есть сначала нумеруется вся строка (2^14=16384 колонок) и только потом идёт переход на следующую строку. То есть Cells(16385) вернёт вам ячейку A2, а D5 будет Cells(65540). Пока данный способ выглядит не очень удобным. |
Работа с диапазоном ячеек
Синтаксическая форма | Комментарии по использованию |
Range(«A1:B4«) или [A1:B4] | Диапазон ячеек A1:B4 текущего листа. Обратите внимание, что указываются координаты верхнего левого и правого нижнего углов диапазона. Причём первый указываемый угол вполне может быть правым нижним, это не имеет значения. |
Range(Cells(1, 1), Cells(4, 2)) | Диапазон ячеек A1:B4 текущего листа. Удобно, когда вы знаете именно цифровые координаты углов диапазона. |
Работа со строками
Синтаксическая форма | Комментарии по использованию |
Range(«3:5«) или [3:5] | Строки 3, 4 и 5 текущего листа целиком. |
Range(«A3:XFD3«) или [A3:XFD3] | Строка 3, но с указанием колонок. Просто, чтобы вы понимали, что это тождественные формы. XFD — последняя колонка листа. |
Rows(«3:3«) | Строка 3 через свойство Rows. Параметр в виде диапазона строк. Двоеточие — это символ диапазона. |
Rows(3) | Тут параметр — индекс строки в массиве строк. Так можно сослаться только не конкретную строку. Обратите внимание, что в предыдущем примере параметр текстовая строка «3:3» и она взята в кавычки, а тут — чистое число. |
Работа со столбцами
Синтаксическая форма | Комментарии по использованию |
Range(«B:B«) или [B:B] | Колонка B текущего листа. |
Range(«B1:B1048576«) или [B1:B1048576] | То же самое, но с указанием номеров строк, чтобы вы понимали, что это тождественные формы. 2^20=1048576 — максимальный номер строки на листе. |
Columns(«B:B«) | То же самое через свойство Columns. Параметр — текстовая строка. |
Columns(2) | То же самое. Параметр — числовой индекс столбца. «A» -> 1, «B» -> 2, и т.д. |
Весь лист
Синтаксическая форма | Комментарии по использованию |
Range(«A1:XFD1048576«) или [A1:XFD1048576] | Диапазон размером во всё адресное пространство листа Excel. Воспринимайте эту таблицу лишь как теорию — так работать с листами вам не придётся — слишком большое количество ячеек. Даже современные компьютеры не смогут помочь Excel быстро работать с такими массивами информации. Тут проблема больше даже в самом приложении. |
Range(«1:1048576«) или [1:1048576] | То же самое, но через строки. |
Range(«A:XFD«) или [A:XFD] | Аналогично — через адреса столбцов. |
Cells | Свойство Cells включает в себя ВСЕ ячейки. |
Rows | Все строки листа. |
Columns | Все столбцы листа. |
Следует иметь в виду, что свойства Range, Cells, Columns и Rows имеют как объекты типа Worksheet, так и объекты Range. Соответственно в первом случае эти коллекции будут относиться ко всему листу и отсчитываться будут от A1, а вот в случае конкретного объекта Range эти коллекции будут относиться только к ячейкам этого диапазона и отсчитываться будут от левого верхнего угла диапазона. Например Cells(2,2) указывает на ячейку B2, а Range(«C3:D5»).Cells(2,2) укажет на D4.
Также много путаницы в умы вносит тот факт, что объект Range имеет одноименное свойство range. К примеру, Range(«A100:D500»).Range(«A2») — тут выражение до точки ( Range(«A100:D500») ) является объектом Range, выражение после точки ( Range(«A2») ) — свойство range упомянутого объекта, но возвращает это свойство тоже объект типа Range. Вот такие пироги. Из этого следует, что такая цепочка может иметь и более двух членов. Практического смысла в этом будет не много, но синтаксически это будут совершенно корректно, например, так: Range(«CV100:GR200»).Range(«J10:T20»).Range(«A1:B2») укажет на диапазон DE109:DF110.
Ещё один сюрприз таится в том, что объекты Range имеют свойство по-умолчанию Item( RowIndex [, ColumnIndex] ). По правилам VBA при ссылке на default свойства имя свойства (Item) можно опускать. Кстати говоря, то что вы привыкли видеть в скобках после Cells, есть не что иное, как это дефолтовое свойство Item, а не родные параметры Cells, который их не имеет вовсе. Ну ладно к Cells все привыкли и это никакого отторжения не вызывает, но если вы увидите нечто подобное — Range(«C3:D5»)(2,2), то, скорее всего, будете несколько озадачены, а тем временем — это буквально тоже самое, что и у Cells — всё то же дефолтовое свойство Item. Последняя конструкция ссылается на D4. А вот для Columns и Rows свойство Item может быть только одночленным, например Columns(1) — и к этой форме мы тоже вполне привыкли. Однако конструкции вида Columns(2)(3)(4) могут сильно удивить (столбец 7 будет выделен).
Примеры кода
Скачать
Типовые задачи
-
Перебор ячеек в диапазоне (вариант 1)
В данном примере организован цикл For…Next и доступ к ячейкам осуществляется по их индексу. Вместо parRange(i) мы могли бы написать parRange.Item(i) (выше это объяснялось). Обратите внимание, что мы в этом примере успешно применяем, как вариант с parRange(i,c), так и parRange(i). То есть, если мы применяем одночленную форму свойства Item, то диапазон перебирается по строкам (A1, B1, C1, A2, …), а если двухчленную, то столбец у нас зафиксирован и каждая итерация цикла — на новой строке. Это очень интересный эффект, его можно применять для вытягивания таблиц по вертикали. Но — продолжим!
Количество ячеек в диапазоне получено при помощи свойства .Count. Как .Item, так и .Count — это всё атрибуты коллекций, которые широко применяются в объектой модели MS Office и, в частности, Excel.
Sub Handle_Cells_1(parRange As Range) For i = 1 To parRange.Count parRange(i, 5) = parRange(i).Address & " = " & parRange(i) Next End Sub
-
Перебор ячеек в диапазоне (вариант 2)
В этом примере мы использовали цикл For each…Next, что выглядит несколько лаконичней. Однако, в некоторых случаях вам может потребоваться переменная i из предыдущего примера, например, для вывода результатов в определенные строки листа, поэтому выбирайте удробную вам форму оператора For. Тут в цикле мы «вытягивали» все ячейки диапазона в текстовую строку, чтобы потом отобразить её через функцию MsgBox.
Sub Handle_Cells_2(parRange As Range) For Each c In parRange strLine = strLine & c.Address & "=" & c & "; " Next MsgBox strLine End Sub
-
Перебор ячеек в диапазоне (вариант 3)
Если необходимо перебирать ячейки в порядке A1, A2, A3, B1, …, а не A1, B1, C1, A2, …, то вы можете это организовать при помощи 2-х циклов For. Обратите внимание, как мы узнали количество столбцов (parRange.Columns.Count) и строк (parRange.Rows.Count) в диапазоне, а также на использование свойства Cells. Тут Cells относится к листу и никак не связано с диапазоном parRange.
Sub Handle_Cells_3(parRange As Range) colNum = parRange.Columns.Count For i = 1 To parRange.Rows.Count For j = 1 To colNum Cells(i + (j - 1) * colNum, colNum + 2) = parRange(i, j) Next j Next i End Sub
-
Перебор строк диапазона
В цикле For each…Next перебираем коллекцию Rows объекта parRange. Для каждой строки формируем цвет на основе первых трёх ячеек каждой строки. Поскульку у нас в ячейках формула, присваивающая ячейке случайное число от 1 до 255, то цвета получаются всегда разные. Оператор With позволяет нам сократить код и, к примеру, вместо Line.Cells(2) написать просто .Cells(2).
Sub Handle_Rows_1(parRange As Range) For Each Line In parRange.Rows With Line .Interior.Color = RGB(.Cells(1), .Cells(2), .Cells(3)) End With Next End Sub
-
Перебор столбцов
Перебираем коллекцию Columns. Тоже используем оператор With. В последней ячейке каждого столбца у нас хранится размер шрифта для всей колонки, который мы и применяем к свойству Line.Font.Size.
Sub Handle_Columns_1(parRange As Range) For Each Line In parRange.Columns With Line .Font.Size = .Cells(.Cells.Count) End With Next End Sub
-
Перебор областей диапазона
Как вы знаете, в Excel можно выделить несвязанные диапазоны и проделать с ними какие-то операции. Поддерживает это и объект Range. Получить диапазон, состоящий из нескольких областей (area) очень легко — достаточно перечислить через запятую адреса соответствующих диапазонов: Range(«A1:B3, B5:D8, Z1:AA12«).
Вот такой составной диапазон и разбирается процедурой, показанной ниже. Организован цикл по коллекции Areas, настроен оператор with на текущий элемент коллекции, и ниже и правее относительно ячейки J1 мы собираем некоторые сведения о свойствах областей составного диапазона (которые каждый по себе, конечно же, тоже являются объектами типа Range). Для задания смещения от ячейки J1 нами впервые использовано очень полезное свойство Offset. Каждый диапазон получает случайный цвет, плюс мы заносим в таблицу порядковый номер диапазона (i), его адрес (.Address), количество ячеек (.Count) и цвет (.Interior.Color) после того, как он вычислен.Sub Handle_Areas_1(parRange As Range) For i = 1 To parRange.Areas.Count With parRange.Areas(i) Cells(1, 10).Offset(i, 0) = i Cells(1, 10).Offset(i, 1) = .Address Cells(1, 10).Offset(i, 2) = .Count .Interior.Color = RGB(Int(Rnd * 255), Int(Rnd * 255), Int(Rnd * 255)) Cells(1, 10).Offset(i, 3) = .Interior.Color End With Next End Sub
Продолжение следует…
Читайте также:
-
Поиск границ текущей области
-
Массивы в VBA
-
Структуры данных и их эффективность
-
Автоматическое скрытие/показ столбцов и строк
Excel VBA Range Object
Range is a property in VBA that helps specify a particular cell, a range of cells, a row, a column, or a three-dimensional range. In the context of the Excel worksheet, the VBA range object includes a single cell or multiple cells spread across various rows and columns.
For example, the range property in VBA is used to refer to specific rows or columns while writing the code. The code “Range(“A1:A5”).Value=2” returns the number 2 in the range A1:A5.
In VBA, macros are recordedRecording macros is a method whereby excel stores the tasks performed by the user. Every time a macro is run, these exact actions are performed automatically. Macros are created in either the View tab (under the “macros” drop-down) or the Developer tab of Excel.
read more and executed to automate the Excel tasks. This helps perform the repetitive processes in a faster and more accurate way. For running the macros, VBA identifies the cells on which the called tasks are to be performed. It is here that the range object in VBA comes in use.
The VBA range property is similar to the worksheet property and has several applications.
Table of contents
- Excel VBA Range Object
- How to use the VBA Range Function in Excel?
- The Syntax of the VBA Range Property
- Example #1–Select a Single Cell
- Example #2–Select an Entire Row
- Example #3–Select an Entire Column
- Example #4–Select Contiguous Cells
- Example #5–Select Non-contiguous Cells
- Example #6–Select a Range Intersection
- Example #7–Merge a Range of Cells
- Example #8–Clear Formatting of a Range
- Frequently Asked Questions
- Recommended Articles
You are free to use this image on your website, templates, etc, Please provide us with an attribution linkArticle Link to be Hyperlinked
For eg:
Source: VBA Range (wallstreetmojo.com)
How to use the VBA Range Function in Excel?
A hierarchy pattern is used in Excel VBA to refer to the range object. This three-level object hierarchy consists of the following elements:
- Object Qualifier: This refers to the location of the object. It is the workbook or the worksheet where the object is placed.
- Property: This stores the information related to the object.
- Method: This refers to the action that the object will perform. For example, for a given range, the methods are actions like sorting, formatting, selecting, clearing, etc.
The given hierarchical structure is to be followed whenever a VBA objectThe “Object Required” error, also known as Error 424, is a VBA run-time error that occurs when you provide an invalid object, i.e., one that is not available in VBA’s object hierarchy.read more is referred. These three elements are separated by the dot operator (.) in the following way:
Application.Workbooks.Worksheets.Range
Note 1: The range object referred by using the given (three-level) hierarchy is known as a fully qualified reference.
Note 2: The “property” and “method” are used for manipulating cell values.
The Syntax of the VBA Range Property
The syntax of the range property in VBA is shown in the following image:
For example, to refer to the cell B1 (range) in “sheet3” (worksheet) of “booknew” (workbook), the following reference is used:
Application.Workbooks(“Booknew.xlsm”).Worksheets(“Sheet3”).Range(“B1”)
You can download this VBA Range Excel Template here – VBA Range Excel Template
Example #1–Select a Single Cell
We want to select the cell B2 in “sheet1” of the workbook.
Step 1: Open the workbook saved with the Excel extensionExcel extensions represent the file format. It helps the user to save different types of excel files in various formats. For instance, .xlsx is used for simple data, and XLSM is used to store the VBA code.read more “.xlsm” (macro-enabled workbook). The “.xlsx” format does not allow saving the macros that are presently being written.
Step 2: Open the VBA editorThe Visual Basic for Applications Editor is a scripting interface. These scripts are primarily responsible for the creation and execution of macros in Microsoft software.read more with the shortcut “ALT+F11.” Alternatively, click “view code” in the “controls” group of the Developer tab, as shown in the following image.
Step 3: The screen, shown in the following image, appears.
Step 4: Enter the following code.
Public Sub SingleCellRange()
ThisWorkbook.Worksheets (“Sheet1”).Range(“B2”).Select
End Sub
With this code, we instruct the program to go to the specified cell (B2) of a particular worksheet and workbook. The action to be performed is to select the given cell.
At present, cell A2 is activated, as shown in the following image.
Step 5: Run the code by clicking “run sub/UserForm” from the Run tab. Alternatively, use the Excel shortcut keyAn Excel shortcut is a technique of performing a manual task in a quicker way.read more F5 to run the code.
Step 6: The result is shown in the following image. The cell B2 is selected after the execution of the program. Hence, after running the code, the activated cell is B2.
Similarly, the code can be modified to select a variety of cells and ranges and perform different actions on them.
Example #2–Select an Entire Row
We want to select the second row in “sheet1” of the workbook.
Step 1: Enter the following code and run it.
Public Sub EntireRowRange()
ThisWorkbook.Worksheets (“Sheet1”).Range(“2:2”).Select
End Sub
The range (“2:2”) in the code represents the second row.
Step 2: The result is shown in the following image. The second row is entirely selected by running the given code.
Example #3–Select an Entire Column
We want to select the column C in “sheet1” of the workbook.
Step 1: Enter the following code and run it.
Public Sub EntireColumnRange()
ThisWorkbook.Worksheets (“Sheet1”).Range(“C:C”).Select
End Sub
The range (“C:C”) in the code represents the column C.
Step 2: The execution of the code and the result is shown in the following image. The column C is entirely selected by running the given code.
Similarly, one can select contiguous and non-contiguous cells, the intersection of cell ranges, etc.
Example #4–Select Contiguous Cells
We want to select the range B2:D6 in “sheet1” of the workbook.
Step 1: Enter the following code and run it.
Public Sub EntireColumnRange()
ThisWorkbook.Worksheets (“Sheet1”).Range(“B2:D6”).Select
End Sub
The range (“B2:D6”) in the code represents the contiguous range B2:D6.
Step 2: The result is shown in the following image. The range B2:D6 is selected by running the given code.
Example #5–Select Non-contiguous Cells
We want to select the ranges B1:C5 and G1:G3 in “sheet1” of the workbook.
Step 1: Enter the following code and run it.
Public Sub EntireColumnRange()
ThisWorkbook.Worksheets (“Sheet1”).Range(“B1:C5, G1:G3”).Select
End Sub
The range (“B1:C5, G1:G3”) in the code represents the two non-contiguous ranges B1:C5 and G1:G3.
Step 2: The result is shown in the following image. The ranges B1:C5 and G1:G3 are selected by running the given code.
Example #6–Select a Range Intersection
We want to select the intersection of two ranges B1:G5 and G1:G3 in “sheet1” of the workbook.
Step 1: Enter the following code and run it.
Public Sub EntireColumnRange()
ThisWorkbook.Worksheets (“Sheet1”).Range(“B1:G5 G1:G3”).Select
End Sub
The range (“B1:G5 G1:G3”) in the code represents the intersection of the two ranges B1:G5 and G1:G3.
Note: The comma within the two ranges is absent in this case.
Step 2: The result is shown in the following image. The cells common to the ranges B1:G5 and G1:G3 are selected by running the given code. Hence, the common cells in the specified range are G1:G3.
Example #7–Merge a Range of Cells
We want to select and merge the cells B1:C5 in “sheet1” of the workbook.
Step 1: Enter the following code and run it.
Public Sub MergeRange()
ThisWorkbook.Worksheets (“Sheet1”).Range(“B1:C5”).Merge
End Sub
The range (“B1:C5”) represents the range B1:C5 on which we are performing the action “merge.”
Step 2: The result is shown in the following image. The cells in the range B1:C5 have been merged by running the given code.
Example #8–Clear Formatting of a Range
The following image shows the range F2:H6, which is highlighted in yellow. We want to clear the Excel formattingFormatting is a useful feature in Excel that allows you to change the appearance of the data in a worksheet. Formatting can be done in a variety of ways. For example, we can use the styles and format tab on the home tab to change the font of a cell or a table.read more on this range in “sheet1” of the workbook.
Step 1: Enter the following code and run it.
Public Sub ClearFormats()
ThisWorkbook.Worksheets(“Sheet1”).Range(“F2:H6”).ClearFormats
End Sub
The range (“F2:H6”) in the given syntaxVBA ThisWorkbook refers to the workbook on which the users currently write the code to execute all of the tasks in the current workbook. In this, it doesn’t matter which workbook is active and only requires the reference to the workbook, where the users write the code.read more represents the range F2:H6 from which we are removing the existing formatting.
Step 2: The result is shown in the following image. The formatting from the cells in the range F2:H6 has been cleared by running the given code.
Similarly, the formatting of the entire worksheet can be removed. Moreover, the content of a range of cells can be cleared by using the action “.ClearContents.”
Frequently Asked Questions
1. Define the VBA range.
The VBA range represents a single cell, a row, a column, a group of cells, or a three-dimensional range. The range must be specified in the following hierarchical pattern:
Application.Workbooks.Worksheets.Range
The references following this format are known as fully qualified references. For simplifying these references, the “application” object can be omitted. In such cases, VBA assumes that the user is working on MS Excel.
For example, a simplified reference is Workbooks(“Book2.xlsm”).Worksheets(“Sheet2”).Range
The basic syntax of the VBA range property consists of the keyword “Range” followed by the parentheses. The relevant range is included within double quotation marks.
For example, the following reference refers to cell C1 in the given worksheet and workbook.
Application.Workbooks(“Book2.xlsm”).Worksheets(“Sheet2”).Range(“C1”)
2. How to copy and paste the VBA range?
The following syntax helps copy the range C1:C5:
Range(“C1:C5”).Copy
The following syntax helps copy the range C1:C5 from the present sheet to “sheet3”:
Range(“C1:C5”).Copy destination:= Worksheets(“Sheet3”).Range(“D1”)
The following syntax helps paste in cell D1 of “sheet3”:
Worksheets(“Sheet3”).Range(“D1”).PasteSpecial
Note: Alternatively, the range can be first selected and the resulting selection can be copied.
3. How to clear cells in a VBA range?
The following syntax helps clear the values, comments, and formats from the range C1:C5:
Range(“C1:C5”).Clear
The following syntax helps clear the content or values from the range C1:C5:
Range(“C1:C5”).ClearContents
Note: The clearing methods “ClearNotes,” “ClearComments,” “ClearOutline,” “ClearHyperlinks,” and so on clear particular types of data from the range.
Recommended Articles
This has been a guide to VBA Range. Here we learn how to select a particular cell and range of cells with the help of VBA range objects and examples in Excel. You may also have a look at other articles related to Excel VBA –
- VBA Application.Match
- Excel VBA Cells Reference
- Use VLookup in VBA
- Using VBA Msg Box