Присвоение диапазона ячеек объектной переменной в VBA Excel. Адресация ячеек в переменной диапазона и работа с ними. Определение размера диапазона. Примеры.
Присвоение диапазона ячеек переменной
Чтобы переменной присвоить диапазон ячеек, она должна быть объявлена как Variant, Object или Range:
Dim myRange1 As Variant Dim myRange2 As Object Dim myRange3 As Range |
Чтобы было понятнее, для чего переменная создана, объявляйте ее как Range.
Присваивается переменной диапазон ячеек с помощью оператора Set:
Set myRange1 = Range(«B5:E16») Set myRange2 = Range(Cells(3, 4), Cells(26, 18)) Set myRange3 = Selection |
В выражении Range(Cells(3, 4), Cells(26, 18)) вместо чисел можно использовать переменные.
Для присвоения диапазона ячеек переменной можно использовать встроенное диалоговое окно Application.InputBox, которое позволяет выбрать диапазон на рабочем листе для дальнейшей работы с ним.
Адресация ячеек в диапазоне
К ячейкам присвоенного диапазона можно обращаться по их индексам, а также по индексам строк и столбцов, на пересечении которых они находятся.
Индексация ячеек в присвоенном диапазоне осуществляется слева направо и сверху вниз, например, для диапазона размерностью 5х5:
1 | 2 | 3 | 4 | 5 |
6 | 7 | 8 | 9 | 10 |
11 | 12 | 13 | 14 | 15 |
16 | 17 | 18 | 19 | 20 |
21 | 22 | 23 | 24 | 25 |
Индексация строк и столбцов начинается с левой верхней ячейки. В диапазоне этого примера содержится 5 строк и 5 столбцов. На пересечении 2 строки и 4 столбца находится ячейка с индексом 9. Обратиться к ней можно так:
‘обращение по индексам строки и столбца myRange.Cells(2, 4) ‘обращение по индексу ячейки myRange.Cells(9) |
Обращаться в переменной диапазона можно не только к отдельным ячейкам, но и к части диапазона (поддиапазону), присвоенного переменной, например,
обращение к первой строке присвоенного диапазона размерностью 5х5:
myRange.Range(«A1:E1») ‘или myRange.Range(Cells(1, 1), Cells(1, 5)) |
и обращение к первому столбцу присвоенного диапазона размерностью 5х5:
myRange.Range(«A1:A5») ‘или myRange.Range(Cells(1, 1), Cells(5, 1)) |
Работа с диапазоном в переменной
Работать с диапазоном в переменной можно точно также, как и с диапазоном на рабочем листе. Все свойства и методы объекта Range действительны и для диапазона, присвоенного переменной. При обращении к ячейке без указания свойства по умолчанию возвращается ее значение. Строки
MsgBox myRange.Cells(6) MsgBox myRange.Cells(6).Value |
равнозначны. В обоих случаях информационное сообщение MsgBox выведет значение ячейки с индексом 6.
Важно: если вы планируете работать только со значениями, используйте переменные массивов, код в них работает значительно быстрее.
Преимущество работы с диапазоном ячеек в объектной переменной заключается в том, что все изменения, внесенные в переменной, применяются к диапазону (который присвоен переменной) на рабочем листе.
Пример 1 — работа со значениями
Скопируйте процедуру в программный модуль и запустите ее выполнение.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
Sub Test1() ‘Объявляем переменную Dim myRange As Range ‘Присваиваем диапазон ячеек Set myRange = Range(«C6:E8») ‘Заполняем первую строку ‘Присваиваем значение первой ячейке myRange.Cells(1, 1) = 5 ‘Присваиваем значение второй ячейке myRange.Cells(1, 2) = 10 ‘Присваиваем третьей ячейке ‘значение выражения myRange.Cells(1, 3) = myRange.Cells(1, 1) _ * myRange.Cells(1, 2) ‘Заполняем вторую строку myRange.Cells(2, 1) = 20 myRange.Cells(2, 2) = 25 myRange.Cells(2, 3) = myRange.Cells(2, 1) _ + myRange.Cells(2, 2) ‘Заполняем третью строку myRange.Cells(3, 1) = «VBA» myRange.Cells(3, 2) = «Excel» myRange.Cells(3, 3) = myRange.Cells(3, 1) _ & » « & myRange.Cells(3, 2) End Sub |
Обратите внимание, что ячейки диапазона на рабочем листе заполнились так же, как и ячейки в переменной диапазона, что доказывает их непосредственную связь между собой.
Пример 2 — работа с форматами
Продолжаем работу с тем же диапазоном рабочего листа «C6:E8»:
Sub Test2() ‘Объявляем переменную Dim myRange As Range ‘Присваиваем диапазон ячеек Set myRange = Range(«C6:E8») ‘Первую строку выделяем жирным шрифтом myRange.Range(«A1:C1»).Font.Bold = True ‘Вторую строку выделяем фоном myRange.Range(«A2:C2»).Interior.Color = vbGreen ‘Третьей строке добавляем границы myRange.Range(«A3:C3»).Borders.LineStyle = True End Sub |
Опять же, обратите внимание, что все изменения форматов в присвоенном диапазоне отобразились на рабочем листе, несмотря на то, что мы непосредственно с ячейками рабочего листа не работали.
Пример 3 — копирование и вставка диапазона из переменной
Значения ячеек диапазона, присвоенного переменной, передаются в другой диапазон рабочего листа с помощью оператора присваивания.
Скопировать и вставить диапазон полностью со значениями и форматами можно при помощи метода Copy, указав место вставки (ячейку) на рабочем листе.
В примере используется тот же диапазон, что и в первых двух, так как он уже заполнен значениями и форматами.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
Sub Test3() ‘Объявляем переменную Dim myRange As Range ‘Присваиваем диапазон ячеек Set myRange = Range(«C6:E8») ‘Присваиваем ячейкам рабочего листа ‘значения ячеек переменной диапазона Range(«A1:C3») = myRange.Value MsgBox «Пауза» ‘Копирование диапазона переменной ‘и вставка его на рабочий лист ‘с указанием начальной ячейки myRange.Copy Range(«E1») MsgBox «Пауза» ‘Копируем и вставляем часть ‘диапазона из переменной myRange.Range(«A2:C2»).Copy Range(«E11») End Sub |
Информационное окно MsgBox добавлено, чтобы вы могли увидеть работу процедуры поэтапно, если решите проверить ее в своей книге Excel.
Размер диапазона в переменной
При получении диапазона с помощью метода Application.InputBox и присвоении его переменной диапазона, бывает полезно узнать его размерность. Это можно сделать следующим образом:
Sub Test4() ‘Объявляем переменную Dim myRange As Range ‘Присваиваем диапазон ячеек Set myRange = Application.InputBox(«Выберите диапазон ячеек:», , , , , , , 8) ‘Узнаем количество строк и столбцов MsgBox «Количество строк = « & myRange.Rows.Count _ & vbNewLine & «Количество столбцов = « & myRange.Columns.Count End Sub |
Запустите процедуру, выберите на рабочем листе Excel любой диапазон и нажмите кнопку «OK». Информационное сообщение выведет количество строк и столбцов в диапазоне, присвоенном переменной myRange.
Set Range in Excel VBA
Set range in VBA means we specify a given range to the code or the procedure to execute. If we do not provide a specific range to a code, it will automatically assume the range from the worksheet with the active cell. So, it is very important in the code to have a range variable set.
After working with Excel for so many years, you must have understood that all works we do are on the worksheet. In worksheets, it is cells containing the data. So when you want to play around with data, you must be a behavior pattern of cells in worksheets. So, when the multiple cells get together, it becomes a RANGE. Therefore, to learn VBA, you should know everything about cells and ranges. So in this article, we will show you how to set the range of cells we can use for VBA codingVBA 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 in detail.
Table of contents
- Set Range in Excel VBA
- How to Access Range of Cells in Excel VBA?
- Accessing Multiple Cells & Setting Range Reference in VBA
- Things to Remember
- 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 Set Range (wallstreetmojo.com)
What is the Range Object?
Range in VBA refers to an object. A range can contain a single cell, multiple cells, a row or column, etc.
In VBA, we can classify the range as below.
“Application >>> Workbook >>> Worksheet >>> Range”
First, we need to access the Application. Then under this, we need to refer to which workbook we are referring to. Next, in the workbook, we are referring to which worksheet we are referring to. Then in the worksheet, we need to mention the range of cells.
Using the Range of cells, we can enter the value to the cell or cells, we can read or get values from the cell or cells, we can delete, we can format, and we can do many other things as well.
How to Access the Range of Cells in Excel VBA?
You can download this VBA Set Range Excel Template here – VBA Set Range Excel Template
In VBA coding, we can refer to the cell using the VBA CELLS propertyCells are cells of the worksheet, and in VBA, when we refer to cells as a range property, we refer to the same cells. In VBA concepts, cells are also the same, no different from normal excel cells.read more and RANGE object. So, for example, if you want to refer to cell A1, we will first see using the RANGE object.
Inside the subprocedure, we need first to open the RANGE object.
Code:
Sub Range_Examples() Range( End Sub
As you can see above, the RANGE object asks what cell we are referring to. So, we need to enter the cell address in double quotes.
Code:
Sub Range_Examples() Range ("A1") End Sub
Once we supply the cell address, we must decide what to do with this cell using properties and methods. Now, put a dot to see the properties and methods of the RANGE object.
If we want to insert the value into the cell, we must choose the “Value” property.
Code:
Sub Range_Examples() Range("A1").Value End Sub
To set a value, we need to put an equal sign and enter the value we want to insert into cell A1.
Code:
Sub Range_Examples() Range("A1").Value = "Excel VBA Class" End Sub
Run the code through the run option and see the magic in cell A1.
As the code mentioned, we have the value in cell A1.
Similarly, we can also refer to the cell using the CELLS property. Open the CELLS property and see the syntax.
It is unlike the RANGE object, where we can enter the cell address directly in double quotes. Rather, we need to give a row number and column to refer to the cell. For example, since we are referring to cell A1, we can say the row is 1, and the column is 1.
After mentioning the cell address, we can use properties and methods to work with cells. But the problem here is unlike the Range object after putting a dot. We do not get to see the IntelliSense list.
So, it would help if you were an expert to refer to the cells using the CELLS property.
Code:
Sub CELLS_Examples() Cells(1, 1).Value = "Excel VBA Class" End Sub
Accessing Multiple Cells & Setting Range Reference in VBA
One of the big differences between CELLS and RANGE is using CELLS. We can access only one cell but using RANGE. We can access multiple cells, as well.
For example, for cells A1 to B5, if we want the value of 50, we can write the code below.
Code:
Sub Range_Examples() Range("A1:B5").Value = 50 End Sub
It will insert the value of 50 from cells A1 to B5.
Instead of referring to the cells directly, we can use the variable to hold the reference of specific cells.
First, define the variable as the “Range” object.
Code:
Sub Range_Examples() Dim Rng As Range End Sub
Once we define the variable as the “Range” object, we need to set the reference for this variable about what the cell addresses will hold the reference to.
To set the reference, we need to use the “SET” keyword and enter the cell addresses using the RANGE object.
Code:
Sub Range_Examples() Dim Rng As Range Set Rng = Range("A1:B5") End Sub
The variable “Rng” refers to the cells A1 to B5.
Instead of writing the cell address Range (“A1:B5”), we can use the variable name “Rng.”
Code:
Sub Range_Examples() Dim Rng As Range Set Rng = Range("A1:B5") Rng.Value = "Range Setting" End Sub
It will insert the mentioned value from the A1 to the B5 cells.
Assume you want whatever the selected cell should be a reference, then we can set the reference as follows.
Code:
Sub Range_Examples() Dim Rng As Range Set Rng = Selection Rng.Value = "Range Setting" End Sub
This one is a beauty because if we select any of the cells and run it, it will also insert the value to those cells.
For example, we will select certain cells.
Now, we will execute the code and see what happens.
For all the selected cells, it has inserted the value.
Like this, we can set the range reference by declaring variables in VBAVariable declaration is necessary in VBA to define a variable for a specific data type so that it can hold values; any variable that is not defined in VBA cannot hold values.read more.
Things to Remember
- The range can select multiple cells, but CELLS can select one cell at a time.
- RANGE is an object, and CELLS is property.
- Any object variable should be the object’s reference using the SET keyword.
Recommended Articles
This article is a guide to VBA Set Range. Here, we discuss setting the range of Excel cells used for reference through VBA code, examples, and a downloadable Excel template. Below you can find some useful Excel VBA articles: –
- VBA Set
- VBA Sort Option
- Range Cells in VBA
- Using Range Objects in VBA
- VBA INT
Excel VBA Set Range
To set the range in VBA is to select the cell where we want to put the required content or to move the cursor to the chosen cell. This helps us in building a code where we can choose the cell we want. If we do not set the range then it will automatically choose the current cell where the cursor is placed. Excel VBA Set Range helps us to choose the range as per user requirements.
In Excel, which is a common fact that whatever we do, contains a cell or table. Either it has numbers or words, everything goes into the cell. It becomes very important for us to know the fact that choosing a cell where we want to place or type of cell contact could be done easily. For that, we have the VBA Set Range, which helps us to put any value in any cell using VBA code where we can select the cell we want.
How to Use Set Range in VBA Excel?
We can choose a cell using a Range object and cell property in VBA. For example, if we want to choose cell A1 from any worksheet then we can use RANGE Object as shown below.
As per the syntax of RANGE Object, where it requires only Cell1, Cell2 as Range. If the number of cells are more than 1 then, instead of type cell name separated by commas we can choose colon (“:“). For example, if we want to select the cell from A1 to C5 then we can use the format as RANGE(“A1:C5”) instead of typing each cell into the Range syntax brackets.
You can download this VBA Set Range Excel Template.xlsm here – VBA Set Range Excel Template.xlsm
Example #1
We will see the example where we will select the range to put anything we want. For this, follow the below steps:
Step 1: Insert a new module inside Visual Basic Editor (VBE). Click on Insert tab > select Module.
Step 2: Write the subprocedure for VBA Set Range as shown below.
Code:
Sub VBA_SetRange() End Sub
Step 3: Declare the variable using DIM as Range object as shown below.
Code:
Sub VBA_SetRange() Dim MyRange As Range End Sub
Step 4: Further setting up the range object with declared variable MyRange, we will then choose the cell which wants to include. Here those cells are A1 to B5.
Code:
Sub VBA_SetRange() Dim MyRange As Range Set MyRange = Range("A1:B5") End Sub
Step 5: Let’s consider a text which we want to insert in the selected range cells as TEST as shown below.
Code:
Sub VBA_SetRange() Dim MyRange As Range Set MyRange = Range("A1:B5") MyRange.Value = "Test" End Sub
Step 6: Once done, run the code after compiling. We will see the chosen cell range A1: B5 has now text as TEST as shown below.
Example #2
There is another way to apply VBA Set Range. In this example, we will see how to set Range in different cell range and choosing the different text into the 2 or more different cell Range. For this, follow the below steps:
Step 1: Open a module and directly write the subprocedure for VBA Set Range.
Code:
Sub VBA_SetRange2() End Sub
Step 2: Open With-End With loop choosing the current worksheet as Sheet1.
Code:
Sub VBA_SetRange2() With Worksheets("Sheet1") End With End Sub
Step 3: Let’s select the cell range choosing cell A1 and putting the value in the cell range A1 as TEST as shown below.
Code:
Sub VBA_SetRange2() With Worksheets("Sheet1") .Range("A1").Value = "Test" End With End Sub
Step 4: Similar to the above-shown step, let’s choose another cell range from cell B2 to C4, choosing the value as MY RANGE as shown below.
Code:
Sub VBA_SetRange2() With Worksheets("Sheet1") .Range("A1").Value = "Test" .Range("B2:C4").Value = "My Range" End With End Sub
Step 5: Now we can run the code if there is no error in compilation found. We would see both the cell of the selected range A1 and cells B2:C4 as shown below with chosen texts.
Example #3
There is another simplest way to choose the VBA Set Range which is the simplest way. For this, follow the below steps:
Step 1: Again open the module and write the subprocedure preferably in the name of VBA Set Range.
Code:
Sub VBA_SetRange3() End Sub
Step 2: Choose the cell where want to set the Range. We have chosen cell A1 as shown below.
Code:
Sub VBA_SetRange3() Range("A1").Value End Sub
Step 3: Put the name or value which we want to insert in the select the Range cell. Here we are choosing MY RANGE again.
Code:
Sub VBA_SetRange3() Range("A1").Value = "My Range" End Sub
Step 4: Now if we run this code, we would see the cell A1 in the current worksheet will have the range value as MY RANGE as shown below.
Pros of VBA Set Range
- It is very easy to implement and also very important to know the way to set the Range in VBA.
- We can choose and set more than 1 Range value using VBA Set Range.
Things to Remember
- VBA Set Range is not limited to the examples which we have seen above. There are many ways to execute VBA Set Range.
- RANGE in VBA is an Object and CELLS are the property that may contain anything.
- We can use CELLS properties as well to set the Range in VBA.
- If we use CELLS instead of RANGE, then we would only be able to set one cell whereas with the help of the RANGE object we can choose any range or combination of cells.
- It is always advised to save the Excel file in Macro enable excel format after writing the VBA Code, to avoid losing the written code in the future.
Recommended Articles
This is a guide to the VBA Set Range. Here we discuss how to use Set Range in excel VBA along with practical examples and downloadable excel templates. You can also go through our other suggested articles –
- How to Use VBA Login?
- VBA Month | Examples With Excel Template
- How to Use Create Object Function in VBA Excel?
- How to Use VBA IsError Function?
In this Article
- Ranges and Cells in VBA
- Cell Address
- Range of Cells
- Writing to Cells
- Reading from Cells
- Non Contiguous Cells
- Intersection of Cells
- Offset from a Cell or Range
- Setting Reference to a Range
- Resize a Range
- OFFSET vs Resize
- All Cells in Sheet
- UsedRange
- CurrentRegion
- Range Properties
- Last Cell in Sheet
- Last Used Row Number in a Column
- Last Used Column Number in a Row
- Cell Properties
- Copy and Paste
- AutoFit Contents
- More Range Examples
- For Each
- Sort
- Find
- Range Address
- Range to Array
- Array to Range
- Sum Range
- Count Range
Ranges and Cells in VBA
Excel spreadsheets store data in Cells. Cells are arranged into Rows and Columns. Each cell can be identified by the intersection point of it’s row and column (Exs. B3 or R3C2).
An Excel Range refers to one or more cells (ex. A3:B4)
Cell Address
A1 Notation
In A1 notation, a cell is referred to by it’s column letter (from A to XFD) followed by it’s row number(from 1 to 1,048,576). This is called a cell address.
In VBA you can refer to any cell using the Range Object.
' Refer to cell B4 on the currently active sheet
MsgBox Range("B4")
' Refer to cell B4 on the sheet named 'Data'
MsgBox Worksheets("Data").Range("B4")
' Refer to cell B4 on the sheet named 'Data' in another OPEN workbook
' named 'My Data'
MsgBox Workbooks("My Data").Worksheets("Data").Range("B4")
R1C1 Notation
In R1C1 Notation a cell is referred by R followed by Row Number then letter ‘C’ followed by the Column Number. eg B4 in R1C1 notation will be referred by R4C2. In VBA you use the Cells Object to use R1C1 notation:
' Refer to cell R[6]C[4] i.e D6
Cells(6, 4) = "D6"
Range of Cells
A1 Notation
To refer to a more than one cell use a “:” between the starting cell address and last cell address. The following will refer to all the cells from A1 to D10:
Range("A1:D10")
R1C1 Notation
To refer to a more than one cell use a “,” between the starting cell address and last cell address. The following will refer to all the cells from A1 to D10:
Range(Cells(1, 1), Cells(10, 4))
Writing to Cells
To write values to a cell or contiguous group of cells, simple refer to the range, put an = sign and then write the value to be stored:
' Store F5 in cell with Address F6
Range("F6") = "F6"
' Store E6 in cell with Address R[6]C[5] i.e E6
Cells(6, 5) = "E6"
' Store A1:D10 in the range A1:D10
Range("A1:D10") = "A1:D10"
' or
Range(Cells(1, 1), Cells(10, 4)) = "A1:D10"
Reading from Cells
To read values from cells, simple refer to the variable to store the values, put an = sign and then refer to the range to be read:
Dim val1
Dim val2
' Read from cell F6
val1 = Range("F6")
' Read from cell E6
val2 = Cells(6, 5)
MsgBox val1
Msgbox val2
Note: To store values from a range of cells, you need to use an Array instead of a simple variable.
Non Contiguous Cells
To refer to non contiguous cells use a comma between the cell addresses:
' Store 10 in cells A1, A3, and A5
Range("A1,A3,A5") = 10
' Store 10 in cells A1:A3 and D1:D3)
Range("A1:A3, D1:D3") = 10
VBA Coding Made Easy
Stop searching for VBA code online. Learn more about AutoMacro — A VBA Code Builder that allows beginners to code procedures from scratch with minimal coding knowledge and with many time-saving features for all users!
Learn More
Intersection of Cells
To refer to non contiguous cells use a space between the cell addresses:
' Store 'Col D' in D1:D10
' which is Common between A1:D10 and D1:F10
Range("A1:D10 D1:G10") = "Col D"
Offset from a Cell or Range
Using the Offset function, you can move the reference from a given Range (cell or group of cells) by the specified number_of_rows, and number_of_columns.
Offset Syntax
Range.Offset(number_of_rows, number_of_columns)
Offset from a cell
' OFFSET from a cell A1
' Refer to cell itself
' Move 0 rows and 0 columns
Range("A1").Offset(0, 0) = "A1"
' Move 1 rows and 0 columns
Range("A1").Offset(1, 0) = "A2"
' Move 0 rows and 1 columns
Range("A1").Offset(0, 1) = "B1"
' Move 1 rows and 1 columns
Range("A1").Offset(1, 1) = "B2"
' Move 10 rows and 5 columns
Range("A1").Offset(10, 5) = "F11"
Offset from a Range
' Move Reference to Range A1:D4 by 4 rows and 4 columns
' New Reference is E5:H8
Range("A1:D4").Offset(4,4) = "E5:H8"
Setting Reference to a Range
To assign a range to a range variable: declare a variable of type Range then use the Set command to set it to a range. Please note that you must use the SET command as RANGE is an object:
' Declare a Range variable
Dim myRange as Range
' Set the variable to the range A1:D4
Set myRange = Range("A1:D4")
' Prints $A$1:$D$4
MsgBox myRange.Address
VBA Programming | Code Generator does work for you!
Resize a Range
Resize method of Range object changes the dimension of the reference range:
Dim myRange As Range
' Range to Resize
Set myRange = Range("A1:F4")
' Prints $A$1:$E$10
Debug.Print myRange.Resize(10, 5).Address
Top-left cell of the Resized range is same as the top-left cell of the original range
Resize Syntax
Range.Resize(number_of_rows, number_of_columns)
OFFSET vs Resize
Offset does not change the dimensions of the range but moves it by the specified number of rows and columns. Resize does not change the position of the original range but changes the dimensions to the specified number of rows and columns.
All Cells in Sheet
The Cells object refers to all the cells in the sheet (1048576 rows and 16384 columns).
' Clear All Cells in Worksheets
Cells.Clear
UsedRange
UsedRange property gives you the rectangular range from the top-left cell used cell to the right-bottom used cell of the active sheet.
Dim ws As Worksheet
Set ws = ActiveSheet
' $B$2:$L$14 if L2 is the first cell with any value
' and L14 is the last cell with any value on the
' active sheet
Debug.Print ws.UsedRange.Address
CurrentRegion
CurrentRegion property gives you the contiguous rectangular range from the top-left cell to the right-bottom used cell containing the referenced cell/range.
Dim myRange As Range
Set myRange = Range("D4:F6")
' Prints $B$2:$L$14
' If there is a filled path from D4:F16 to B2 AND L14
Debug.Print myRange.CurrentRegion.Address
' You can refer to a single starting cell also
Set myRange = Range("D4") ' Prints $B$2:$L$14
AutoMacro | Ultimate VBA Add-in | Click for Free Trial!
Range Properties
You can get Address, row/column number of a cell, and number of rows/columns in a range as given below:
Dim myRange As Range
Set myRange = Range("A1:F10")
' Prints $A$1:$F$10
Debug.Print myRange.Address
Set myRange = Range("F10")
' Prints 10 for Row 10
Debug.Print myRange.Row
' Prints 6 for Column F
Debug.Print myRange.Column
Set myRange = Range("E1:F5")
' Prints 5 for number of Rows in range
Debug.Print myRange.Rows.Count
' Prints 2 for number of Columns in range
Debug.Print myRange.Columns.Count
Last Cell in Sheet
You can use Rows.Count and Columns.Count properties with Cells object to get the last cell on the sheet:
' Print the last row number
' Prints 1048576
Debug.Print "Rows in the sheet: " & Rows.Count
' Print the last column number
' Prints 16384
Debug.Print "Columns in the sheet: " & Columns.Count
' Print the address of the last cell
' Prints $XFD$1048576
Debug.Print "Address of Last Cell in the sheet: " & Cells(Rows.Count, Columns.Count)
Last Used Row Number in a Column
END property takes you the last cell in the range, and End(xlUp) takes you up to the first used cell from that cell.
Dim lastRow As Long
lastRow = Cells(Rows.Count, "A").End(xlUp).Row
Last Used Column Number in a Row
Dim lastCol As Long
lastCol = Cells(1, Columns.Count).End(xlToLeft).Column
END property takes you the last cell in the range, and End(xlToLeft) takes you left to the first used cell from that cell.
You can also use xlDown and xlToRight properties to navigate to the first bottom or right used cells of the current cell.
AutoMacro | Ultimate VBA Add-in | Click for Free Trial!
Cell Properties
Common Properties
Here is code to display commonly used Cell Properties
Dim cell As Range
Set cell = Range("A1")
cell.Activate
Debug.Print cell.Address
' Print $A$1
Debug.Print cell.Value
' Prints 456
' Address
Debug.Print cell.Formula
' Prints =SUM(C2:C3)
' Comment
Debug.Print cell.Comment.Text
' Style
Debug.Print cell.Style
' Cell Format
Debug.Print cell.DisplayFormat.NumberFormat
Cell Font
Cell.Font object contains properties of the Cell Font:
Dim cell As Range
Set cell = Range("A1")
' Regular, Italic, Bold, and Bold Italic
cell.Font.FontStyle = "Bold Italic"
' Same as
cell.Font.Bold = True
cell.Font.Italic = True
' Set font to Courier
cell.Font.FontStyle = "Courier"
' Set Font Color
cell.Font.Color = vbBlue
' or
cell.Font.Color = RGB(255, 0, 0)
' Set Font Size
cell.Font.Size = 20
Copy and Paste
Paste All
Ranges/Cells can be copied and pasted from one location to another. The following code copies all the properties of source range to destination range (equivalent to CTRL-C and CTRL-V)
'Simple Copy
Range("A1:D20").Copy
Worksheets("Sheet2").Range("B10").Paste
'or
' Copy from Current Sheet to sheet named 'Sheet2'
Range("A1:D20").Copy destination:=Worksheets("Sheet2").Range("B10")
Paste Special
Selected properties of the source range can be copied to the destination by using PASTESPECIAL option:
' Paste the range as Values only
Range("A1:D20").Copy
Worksheets("Sheet2").Range("B10").PasteSpecial Paste:=xlPasteValues
Here are the possible options for the Paste option:
' Paste Special Types
xlPasteAll
xlPasteAllExceptBorders
xlPasteAllMergingConditionalFormats
xlPasteAllUsingSourceTheme
xlPasteColumnWidths
xlPasteComments
xlPasteFormats
xlPasteFormulas
xlPasteFormulasAndNumberFormats
xlPasteValidation
xlPasteValues
xlPasteValuesAndNumberFormats
AutoFit Contents
Size of rows and columns can be changed to fit the contents using AutoFit:
' Change size of rows 1 to 5 to fit contents
Rows("1:5").AutoFit
' Change size of Columns A to B to fit contents
Columns("A:B").AutoFit
More Range Examples
It is recommended that you use Macro Recorder while performing the required action through the GUI. It will help you understand the various options available and how to use them.
AutoMacro | Ultimate VBA Add-in | Click for Free Trial!
For Each
It is easy to loop through a range using For Each construct as show below:
For Each cell In Range("A1:B100")
' Do something with the cell
Next cell
At each iteration of the loop one cell in the range is assigned to the variable cell and statements in the For loop are executed for that cell. Loop exits when all the cells are processed.
Sort
Sort is a method of Range object. You can sort a range by specifying options for sorting to Range.Sort. The code below will sort the columns A:C based on key in cell C2. Sort Order can be xlAscending or xlDescending. Header:= xlYes should be used if first row is the header row.
Columns("A:C").Sort key1:=Range("C2"), _
order1:=xlAscending, Header:=xlYes
Find
Find is also a method of Range Object. It find the first cell having content matching the search criteria and returns the cell as a Range object. It return Nothing if there is no match.
Use FindNext method (or FindPrevious) to find next(previous) occurrence.
Following code will change the font to “Arial Black” for all cells in the range which start with “John”:
For Each c In Range("A1:A100")
If c Like "John*" Then
c.Font.Name = "Arial Black"
End If
Next c
Following code will replace all occurrences of “To Test” to “Passed” in the range specified:
With Range("a1:a500")
Set c = .Find("To Test", LookIn:=xlValues)
If Not c Is Nothing Then
firstaddress = c.Address
Do
c.Value = "Passed"
Set c = .FindNext(c)
Loop While Not c Is Nothing And c.Address <> firstaddress
End If
End With
It is important to note that you must specify a range to use FindNext. Also you must provide a stopping condition otherwise the loop will execute forever. Normally address of the first cell which is found is stored in a variable and loop is stopped when you reach that cell again. You must also check for the case when nothing is found to stop the loop.
Range Address
Use Range.Address to get the address in A1 Style
MsgBox Range("A1:D10").Address
' or
Debug.Print Range("A1:D10").Address
Use xlReferenceStyle (default is xlA1) to get addres in R1C1 style
MsgBox Range("A1:D10").Address(ReferenceStyle:=xlR1C1)
' or
Debug.Print Range("A1:D10").Address(ReferenceStyle:=xlR1C1)
This is useful when you deal with ranges stored in variables and want to process for certain addresses only.
AutoMacro | Ultimate VBA Add-in | Click for Free Trial!
Range to Array
It is faster and easier to transfer a range to an array and then process the values. You should declare the array as Variant to avoid calculating the size required to populate the range in the array. Array’s dimensions are set to match number of values in the range.
Dim DirArray As Variant
' Store the values in the range to the Array
DirArray = Range("a1:a5").Value
' Loop to process the values
For Each c In DirArray
Debug.Print c
Next
Array to Range
After processing you can write the Array back to a Range. To write the Array in the example above to a Range you must specify a Range whose size matches the number of elements in the Array.
Use the code below to write the Array to the range D1:D5:
Range("D1:D5").Value = DirArray
Range("D1:H1").Value = Application.Transpose(DirArray)
Please note that you must Transpose the Array if you write it to a row.
Sum Range
SumOfRange = Application.WorksheetFunction.Sum(Range("A1:A10"))
Debug.Print SumOfRange
You can use many functions available in Excel in your VBA code by specifying Application.WorkSheetFunction. before the Function Name as in the example above.
Count Range
' Count Number of Cells with Numbers in the Range
CountOfCells = Application.WorksheetFunction.Count(Range("A1:A10"))
Debug.Print CountOfCells
' Count Number of Non Blank Cells in the Range
CountOfNonBlankCells = Application.WorksheetFunction.CountA(Range("A1:A10"))
Debug.Print CountOfNonBlankCells
Written by: Vinamra Chandra
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