Excel VBA Columns Property
We all are well aware of the fact that an Excel Worksheet is arranged in columns and rows and each intersection of rows and columns is considered as a cell. Whenever we want to refer a cell in Excel through VBA, we can use the Range or Cells properties. What if we want to refer the columns from Excel worksheet? Is there any function which we can use to refer the same? The answer is a big YES!
Yes, there is a property in VBA called “Columns” which helps you in referring as well as returning the column from given Excel Worksheet. We can refer any column from the worksheet using this property and can manipulate the same.
Syntax of VBA Columns:
The syntax for VBA Columns property is as shown below:
Where,
- RowIndex – Represents the row number from which the cells have to be retrieved.
- ColumnIndex – Represents the column number which is in an intersection with the respective rows and cells.
Obviously, which column needs to be included/used for further proceedings is being used by these two arguments. Both are optional and if not provided by default would be considered as the first row and first column.
How to Use Columns Property in Excel VBA?
Below are the different examples to use columns property in excel using VBA code.
You can download this VBA Columns Excel Template here – VBA Columns Excel Template
Example #1 – Select Column using VBA Columns Property
We will see how a column can be selected from a worksheet using VBA Columns property. For this, follow the below steps:
Step 1: Insert a new module under Visual Basic Editor (VBE) where you can write the block of codes. Click on Insert tab and select Module in VBA pane.
Step 2: Define a new sub-procedure which can hold the macro you are about to write.
Code:
Sub Example_1() End Sub
Step 3: Use Columns.Select property from VBA to select the first column from your worksheet. This actually has different ways, you can use Columns(1).Select initially. See the screenshot below:
Code:
Sub Example_1() Columns(1).Select End Sub
The Columns property in this small piece of code specifies the column number and Select property allows the VBA to select the column. Therefore in this code, Column 1 is selected based on the given inputs.
Step 4: Hit F5 or click on the Run button to run this code and see the output. You can see that column 1 will be selected in your excel sheet.
This is one way to use columns property to select a column from a worksheet. We can also use the column names instead of column numbers in the code. Below code also gives the same result.
Code:
Sub Example_1() Columns("A").Select End Sub
Example #2 – VBA Columns as a Worksheet Function
If we are using the Columns property without any qualifier, then it will only work on all the Active worksheets present in a workbook. However, in order to make the code more secure, we can use the worksheet qualifier with columns and make our code more secure. Follow the steps below:
Step 1: Define a new sub-procedure which can hold the macro under the module.
Code:
Sub Example_2() End Sub
Now we are going to use Worksheets.Columns property to select a column from a specified worksheet.
Step 2: Start typing the Worksheets qualifier under given macro. This qualifier needs the name of the worksheet, specify the sheet name as “Example 2” (Don’t forget to add the parentheses). This will allow the system to access the worksheet named Example 2 from the current workbook.
Code:
Sub Example_2() Worksheets("Example 2") End Sub
Step 3: Now use Columns property which will allow you to perform different column operations on a selected worksheet. I will choose the 4th column. I either can choose it by writing the index as 4 or specifying the column alphabet which is “D”.
Code:
Sub Example_2() Worksheets("Example 2").Columns("D") End Sub
As of here, we have selected a worksheet named Example 2 and accessed the column D from it. Now, we need to perform some operations on the column accessed.
Step 4: Use Select property after Columns to select the column specified in the current worksheet.
Code:
Sub Example_2() Worksheets("Example 2").Columns("D").Select End Sub
Step 5: Run the code by pressing the F5 key or by clicking on Play Button.
Example #3 – VBA Columns Property to Select Range of Cells
Suppose we want to select the range of cells across different columns. We can combine the Range as well as Columns property to do so. Follow the steps below:
Suppose we have our data spread across B1 to D4 in the worksheet as shown below:
Step 1: Define a new sub-procedure to hold a macro.
Code:
Sub Example_3() End Sub
Step 2: Use the Worksheets qualifier to be able to access the worksheet named “Example 3” where we have the data shown in the above screenshot.
Code:
Sub Example_3() Worksheets("Example 3") End Sub
Step 3: Use Range property to set the range for this code from B1 to D4. Use the following code Range(“B1:D4”) for the same.
Code:
Sub Example_3() Worksheets("Example 3").Range("B1:D4") End Sub
Step 4: Use Columns property to access the second column from the selection. Use code as Columns(2) in order to access the second column from the accessed range.
Code:
Sub Example_3() Worksheets("Example 3").Range("B1:D4").Columns(2) End Sub
Step 5: Now, the most important part. We have accessed the worksheet, range, and column. However, in order to select the accessed content, we need to use Select property in VBA. See the screenshot below for the code layout.
Code:
Sub Example_3() Worksheets("Example 3").Range("B1:D4").Columns(2).Select End Sub
Step 6: Run this code by hitting F5 or Run button and see the output.
You can see the code has selected Column C from the excel worksheet though you have put the column value as 2 (which means the second column). The reason for this is, we have chosen the range as B1:D4 in this code. Which consists of three columns B, C, D. At the time of execution column B is considered as first column, C as second and D as the third column instead of their actual positionings. The range function has reduced the scope for this function for B1:D4 only.
Things to Remember
- We can’t see the IntelliSense list of properties when we are working on VBA Columns.
- This property is categorized under Worksheet property in VBA.
Recommended Articles
This is a guide to VBA Columns. Here we discuss how to use columns property in Excel by using VBA code along with practical examples and downloadable excel template. You can also go through our other suggested articles –
- VBA Insert Column
- Grouping Columns in Excel
- VBA Delete Column
- Switching Columns in Excel
Excel VBA Columns Property
VBA Columns property is used to refer to columns in the worksheet. Using this property we can use any column in the specified worksheet and work with it.
When we want to refer to the cell, we use either the Range object or Cells property. Similarly, how do you refer to columns in VBA? We can refer to columns by using the “Columns” property. Look at the syntax of COLUMNS property.
Table of contents
- Excel VBA Columns Property
- Examples
- Example #1
- Example #2 – Select Column Based on Variable Value
- Example #3 – Select Column Based on Cell Value
- Example #4 – Combination of Range & Column Property
- Example #5 – Select Multiple Columns with Range Object
- Recommended Articles
- Examples
We need to mention the column number or header alphabet to reference the column.
For example, if we want to refer to the second column, we can write the code in three ways.
Columns (2)
Columns(“B:B”)
Range (“B:B”)
Examples
You can download this VBA Columns Excel Template here – VBA Columns Excel Template
Example #1
If you want to select the second column in the worksheet, then first, we need to mention the column number we need to select.
Code:
Sub Columns_Example() Columns (2) End Sub
Now, put a dot (.) to choose the “Select” method.
One of the problems with this property is we do not get to see the IntelliSense list of VBA.
Code:
Sub Columns_Example() Columns(2).Select End Sub
So, the above VBA codeVBA code refers to a set of instructions written by the user in the Visual Basic Applications programming language on a Visual Basic Editor (VBE) to perform a specific task.read more will select the second column of the worksheet.
Instead of mentioning the column number, we can use the column header alphabet “B” to select the second column.
Code:
Sub Columns_Example() Columns("B").Select Columns("B:B").Select End Sub
The above codes will select column B, i.e., the second column.
Example #2 – Select Column Based on Variable Value
We can also use the variable to select the column number. For example, look at the below code now.
Code:
Sub Columns_Example() Dim ColNum As Integer ColNum = 4 Columns(ColNum).Select End Sub
In the above, we have declared the variable as “Integer” and assigned the value of 4 to this variable.
We have supplied this variable instead of the column number for the Column’s property. Since the variable holds the value of 4, it will select the 4th column.
Example #3 – Select Column Based on Cell Value
We have seen how to select the column based on variable value now. Next, we will see how we can select the column based on the cell value number. For example, in cell A1 we have entered the number 3.
The code below will select the column based on the number in cell A1.
Code:
Sub Columns_Example() Dim ColNum As Integer ColNum = Range("A1").Value Columns(ColNum).Select End Sub
The above code is the same as the previous one. Still, the only thing we have changed here is instead of assigning the direct number to the variable. Instead, we gave a variable value as “whatever the number is in cell A1.”
Since we have a value of 3 in cell A1, it will select the third column.
Example #4 – Combination of Range & Column Property
We can also use the Columns property with the Range object. Using the Range object, we can specify the specific range. For example, look at the below code.
Code:
Sub Columns_Example1() Range("C1:D5").Columns(2).Select End Sub
In the above example, we have specified the range of cells as C1 to D5. Then, using the columns property, we have specified the column number as 2 to select.
Now, in general, our second column is B. So the code has to select the “B” column but see what happens when we run the code.
It has selected the cells from D1 to D5.
In our perception, it should have selected the second column, i.e., column B. But now, it has selected the cells from D1 to D5.
It has selected these cells because before using the COLUMNS property, we have specified the range using the RANGE object as C1 to D5. Now, the property thinks within this range as the columns and selects the second column in the range C1 to D5. Therefore, D is the second column, and specified cells are D1 to D5.
Example #5 – Select Multiple Columns with Range Object
Using the Range object and Columns property, we can select multiple columns. For example, look at the below code.
Code:
Sub Columns_Example1() Range(Columns(2), Columns(5)).Select End Sub
The code will select the column from the second column to the fifth column, i.e., from column B to E.
We can also write the code in this way.
Code:
Sub Columns_Example1() Range(Columns(B), Columns(E)).Select End Sub
The above is the same as the previous one and selects the columns from B to E.
Like this, we can use the COLUMNS property to work with the worksheet.
Recommended Articles
This article has been a guide to VBA Columns. Here, we discuss examples of the column property in Excel VBA and select multiple columns with the range object and downloadable Excel templates. Below are some useful articles related to VBA: –
- DateSerial Function in Excel VBA
- Hide Columns in VBA
- Insert Columns in VBA
- Delete Column in VBA
- VBA Variable Types
Содержание
- Свойство Range.Columns (Excel)
- Синтаксис
- Замечания
- Пример
- Поддержка и обратная связь
- Range.Columns property (Excel)
- Syntax
- Remarks
- Example
- Support and feedback
- Refer to Rows and Columns
- About the Contributor
- Support and feedback
- Using the Excel Range Columns property in VBA
- Set Columns as Range
- N-th item in the collection
- Counting columns and cells
- Column in range and EntireColumn
- Select one or more columns in the columns collection using column character
- Loop over columns in Range
- VBA Columns
- Excel VBA Columns Property
- How to Use Columns Property in Excel VBA?
- Example #1 – Select Column using VBA Columns Property
- Example #2 – VBA Columns as a Worksheet Function
- Example #3 – VBA Columns Property to Select Range of Cells
- Things to Remember
- Recommended Articles
Свойство Range.Columns (Excel)
Возвращает объект Range , представляющий столбцы в указанном диапазоне.
Синтаксис
expression. Столбцы
выражение: переменная, представляющая объект Range.
Замечания
Чтобы вернуть один столбец, используйте свойство Item или аналогично включите индекс в круглые скобки. Например, и Selection.Columns(1) возвращают Selection.Columns.Item(1) первый столбец выделенного фрагмента.
При применении к объекту Range , который является выделенным с несколькими областями, это свойство возвращает столбцы только из первой области диапазона. Например, если объект Range имеет две области — A1:B2 и C3:D4, возвращает Selection.Columns.Count значение 2, а не 4. Чтобы использовать это свойство в диапазоне, который может содержать выбор из нескольких областей, проверьте Areas.Count , содержит ли диапазон несколько областей. Если это так, выполните цикл по каждой области в диапазоне.
Возвращаемый диапазон может находиться за пределами указанного диапазона. Например, Range(«A1:B2»).Columns(5).Select возвращает ячейки E1:E2.
Если буква используется в качестве индекса, она эквивалентна числу. Например, Range(«B1:C10»).Columns(«B»).Select возвращает ячейки C1:C10, а не ячейки B1:B10. В примере «B» эквивалентно 2.
Использование свойства Columns без квалификатора объекта эквивалентно использованию ActiveSheet.Columns . Дополнительные сведения см. в свойстве Worksheet.Columns .
Пример
В этом примере для каждой ячейки в столбце один в диапазоне с именем myRange задается значение 0 (ноль).
В этом примере отображается количество столбцов в выделенном фрагменте на листе Sheet1. Если выбрано несколько областей, в примере выполняется цикл по каждой области.
Поддержка и обратная связь
Есть вопросы или отзывы, касающиеся Office VBA или этой статьи? Руководство по другим способам получения поддержки и отправки отзывов см. в статье Поддержка Office VBA и обратная связь.
Источник
Range.Columns property (Excel)
Returns a Range object that represents the columns in the specified range.
Syntax
expression.Columns
expression A variable that represents a Range object.
To return a single column, use the Item property or equivalently include an index in parentheses. For example, both Selection.Columns(1) and Selection.Columns.Item(1) return the first column of the selection.
When applied to a Range object that is a multiple-area selection, this property returns columns from only the first area of the range. For example, if the Range object has two areas—A1:B2 and C3:D4— Selection.Columns.Count returns 2, not 4. To use this property on a range that may contain a multiple-area selection, test Areas.Count to determine whether the range contains more than one area. If it does, loop over each area in the range.
The returned range might be outside the specified range. For example, Range(«A1:B2»).Columns(5).Select returns cells E1:E2.
If a letter is used as an index, it is equivalent to a number. For example, Range(«B1:C10»).Columns(«B»).Select returns cells C1:C10, not cells B1:B10. In the example, «B» is equivalent to 2.
Using the Columns property without an object qualifier is equivalent to using ActiveSheet.Columns . For more information, see the Worksheet.Columns property.
Example
This example sets the value of every cell in column one in the range named myRange to 0 (zero).
This example displays the number of columns in the selection on Sheet1. If more than one area is selected, the example loops through each area.
Support and feedback
Have questions or feedback about Office VBA or this documentation? Please see Office VBA support and feedback for guidance about the ways you can receive support and provide feedback.
Источник
Refer to Rows and Columns
Use the Rows property or the Columns property to work with entire rows or columns. These properties return a Range object that represents a range of cells. In the following example, Rows(1) returns row one on Sheet1. The Bold property of the Font object for the range is then set to True.
The following table illustrates some row and column references using the Rows and Columns properties.
Reference | Meaning |
---|---|
Rows(1) | Row one |
Rows | All the rows on the worksheet |
Columns(1) | Column one |
Columns(«A») | Column one |
Columns | All the columns on the worksheet |
To work with several rows or columns at the same time, create an object variable and use the Union method, combining multiple calls to the Rows or Columns property. The following example changes the format of rows one, three, and five on worksheet one in the active workbook to bold.
Sample code provided by: Dennis Wallentin, VSTO & .NET & Excel This example deletes the empty rows from a selected range.
This example deletes the empty columns from a selected range.
About the Contributor
Dennis Wallentin is the author of VSTO & .NET & Excel, a blog that focuses on .NET Framework solutions for Excel and Excel Services. Dennis has been developing Excel solutions for over 20 years and is also the coauthor of «Professional Excel Development: The Definitive Guide to Developing Applications Using Microsoft Excel, VBA and .NET (2nd Edition).»
Support and feedback
Have questions or feedback about Office VBA or this documentation? Please see Office VBA support and feedback for guidance about the ways you can receive support and provide feedback.
Источник
Using the Excel Range Columns property in VBA
The following sections explain how you can use worksheet or range object .Columns property. It begins with explaining several ways to select a column. At the end, I will explain how to loop over the columns collection.
Set Columns as Range
The .Columns property returns a range as a collection of columns, the selected range of columns. Which columns are included is determined by the RowIndex and ColumnIndex properties as explained below. There are three classes that support the Columns property:
- Application.Columns : All columns on the active worksheet. This is what is assumed when Columns is called without specifying the range or worksheet.
- Worksheets(«Sheet1»).Columns(«B:D») : columns B, C and D on the specified worksheet.
- Range(«B2:D3»).Columns(2) : The second columns in the specified range, here C.
There are two ways to identify column(s) in the Columns collection:
- N-th item in the columns collection
- Select column in the columns collection using column character
Another ways to identify a column is using the range address, e.g. Range(«B:B») , or Range(«B:D») for columns B, C and D.
N-th item in the collection
When leaving out the second optional argument ColumnIndex , the Columns property returns the nth item. The order in which items get returned is breadth-first, so in the example table the columns with value a,b,c. f.
Expression | Value | Comment |
---|---|---|
Range(«B2:C3»).Columns(2) | C | The second column in the range |
Range(«B2:C3»).Columns(3) | D | Even though the range only has two columns, . |
Note |
---|
Negative values in the index are not allowed. |
Counting columns and cells
Range(«B2:C3»).Columns.Count returns 2 columns, Range(«B2:C3»).Columns.Cells.Count returns 4 cells.
Column in range and EntireColumn
As shown in above example, Columns applied to a range only includes the cells in that range. To get the complete column, apply EntireColumn .
Select one or more columns in the columns collection using column character
Expression | Column | Comment |
---|---|---|
Range(«B2:B3»).Columns(«B») | C | Column character interpreted as number, e.g. «B» is always 2nd column, even if not in the original range |
Range(«B2:B3»).Columns(«B:C») | C and D | Column character interpreted as number, e.g. «B» is always 2nd column |
Loop over columns in Range
The Columns property is particularly useful because it makes it easy to iterate over a range. The image below shows the part of the Code VBA (download) menu that lets you insert the code fragment you require.
Источник
VBA Columns
Excel VBA Columns Property
We all are well aware of the fact that an Excel Worksheet is arranged in columns and rows and each intersection of rows and columns is considered as a cell. Whenever we want to refer a cell in Excel through VBA, we can use the Range or Cells properties. What if we want to refer the columns from Excel worksheet? Is there any function which we can use to refer the same? The answer is a big YES!
Yes, there is a property in VBA called “Columns” which helps you in referring as well as returning the column from given Excel Worksheet. We can refer any column from the worksheet using this property and can manipulate the same.
Valuation, Hadoop, Excel, Mobile Apps, Web Development & many more.
Syntax of VBA Columns:
The syntax for VBA Columns property is as shown below:
- RowIndex – Represents the row number from which the cells have to be retrieved.
- ColumnIndex – Represents the column number which is in an intersection with the respective rows and cells.
Obviously, which column needs to be included/used for further proceedings is being used by these two arguments. Both are optional and if not provided by default would be considered as the first row and first column.
How to Use Columns Property in Excel VBA?
Below are the different examples to use columns property in excel using VBA code.
Example #1 – Select Column using VBA Columns Property
We will see how a column can be selected from a worksheet using VBA Columns property. For this, follow the below steps:
Step 1: Insert a new module under Visual Basic Editor (VBE) where you can write the block of codes. Click on Insert tab and select Module in VBA pane.
Step 2: Define a new sub-procedure which can hold the macro you are about to write.
Code:
Step 3: Use Columns.Select property from VBA to select the first column from your worksheet. This actually has different ways, you can use Columns(1).Select initially. See the screenshot below:
Code:
The Columns property in this small piece of code specifies the column number and Select property allows the VBA to select the column. Therefore in this code, Column 1 is selected based on the given inputs.
Step 4: Hit F5 or click on the Run button to run this code and see the output. You can see that column 1 will be selected in your excel sheet.
This is one way to use columns property to select a column from a worksheet. We can also use the column names instead of column numbers in the code. Below code also gives the same result.
Code:
Example #2 – VBA Columns as a Worksheet Function
If we are using the Columns property without any qualifier, then it will only work on all the Active worksheets present in a workbook. However, in order to make the code more secure, we can use the worksheet qualifier with columns and make our code more secure. Follow the steps below:
Step 1: Define a new sub-procedure which can hold the macro under the module.
Code:
Now we are going to use Worksheets.Columns property to select a column from a specified worksheet.
Step 2: Start typing the Worksheets qualifier under given macro. This qualifier needs the name of the worksheet, specify the sheet name as “Example 2” (Don’t forget to add the parentheses). This will allow the system to access the worksheet named Example 2 from the current workbook.
Code:
Step 3: Now use Columns property which will allow you to perform different column operations on a selected worksheet. I will choose the 4 th column. I either can choose it by writing the index as 4 or specifying the column alphabet which is “D”.
Code:
As of here, we have selected a worksheet named Example 2 and accessed the column D from it. Now, we need to perform some operations on the column accessed.
Step 4: Use Select property after Columns to select the column specified in the current worksheet.
Code:
Step 5: Run the code by pressing the F5 key or by clicking on Play Button.
Example #3 – VBA Columns Property to Select Range of Cells
Suppose we want to select the range of cells across different columns. We can combine the Range as well as Columns property to do so. Follow the steps below:
Suppose we have our data spread across B1 to D4 in the worksheet as shown below:
Step 1: Define a new sub-procedure to hold a macro.
Code:
Step 2: Use the Worksheets qualifier to be able to access the worksheet named “Example 3” where we have the data shown in the above screenshot.
Code:
Step 3: Use Range property to set the range for this code from B1 to D4. Use the following code Range(“B1:D4”) for the same.
Code:
Step 4: Use Columns property to access the second column from the selection. Use code as Columns(2) in order to access the second column from the accessed range.
Code:
Step 5: Now, the most important part. We have accessed the worksheet, range, and column. However, in order to select the accessed content, we need to use Select property in VBA. See the screenshot below for the code layout.
Code:
Step 6: Run this code by hitting F5 or Run button and see the output.
You can see the code has selected Column C from the excel worksheet though you have put the column value as 2 (which means the second column). The reason for this is, we have chosen the range as B1:D4 in this code. Which consists of three columns B, C, D. At the time of execution column B is considered as first column, C as second and D as the third column instead of their actual positionings. The range function has reduced the scope for this function for B1:D4 only.
Things to Remember
- We can’t see the IntelliSense list of properties when we are working on VBA Columns.
- This property is categorized under Worksheet property in VBA.
Recommended Articles
This is a guide to VBA Columns. Here we discuss how to use columns property in Excel by using VBA code along with practical examples and downloadable excel template. You can also go through our other suggested articles –
Источник
“It is a capital mistake to theorize before one has data”- Sir Arthur Conan Doyle
This post covers everything you need to know about using Cells and Ranges in VBA. You can read it from start to finish as it is laid out in a logical order. If you prefer you can use the table of contents below to go to a section of your choice.
Topics covered include Offset property, reading values between cells, reading values to arrays and formatting cells.
A Quick Guide to Ranges and Cells
Function | Takes | Returns | Example | Gives |
---|---|---|---|---|
Range |
cell address | multiple cells | .Range(«A1:A4») | $A$1:$A$4 |
Cells | row, column | one cell | .Cells(1,5) | $E$1 |
Offset | row, column | multiple cells | Range(«A1:A2») .Offset(1,2) |
$C$2:$C$3 |
Rows | row(s) | one or more rows | .Rows(4) .Rows(«2:4») |
$4:$4 $2:$4 |
Columns | column(s) | one or more columns | .Columns(4) .Columns(«B:D») |
$D:$D $B:$D |
Download the Code
The Webinar
If you are a member of the VBA Vault, then click on the image below to access the webinar and the associated source code.
(Note: Website members have access to the full webinar archive.)
Introduction
This is the third post dealing with the three main elements of VBA. These three elements are the Workbooks, Worksheets and Ranges/Cells. Cells are by far the most important part of Excel. Almost everything you do in Excel starts and ends with Cells.
Generally speaking, you do three main things with Cells
- Read from a cell.
- Write to a cell.
- Change the format of a cell.
Excel has a number of methods for accessing cells such as Range, Cells and Offset.These can cause confusion as they do similar things and can lead to confusion
In this post I will tackle each one, explain why you need it and when you should use it.
Let’s start with the simplest method of accessing cells – using the Range property of the worksheet.
Important Notes
I have recently updated this article so that is uses Value2.
You may be wondering what is the difference between Value, Value2 and the default:
' Value2 Range("A1").Value2 = 56 ' Value Range("A1").Value = 56 ' Default uses value Range("A1") = 56
Using Value may truncate number if the cell is formatted as currency. If you don’t use any property then the default is Value.
It is better to use Value2 as it will always return the actual cell value(see this article from Charle Williams.)
The Range Property
The worksheet has a Range property which you can use to access cells in VBA. The Range property takes the same argument that most Excel Worksheet functions take e.g. “A1”, “A3:C6” etc.
The following example shows you how to place a value in a cell using the Range property.
' https://excelmacromastery.com/ Public Sub WriteToCell() ' Write number to cell A1 in sheet1 of this workbook ThisWorkbook.Worksheets("Sheet1").Range("A1").Value2 = 67 ' Write text to cell A2 in sheet1 of this workbook ThisWorkbook.Worksheets("Sheet1").Range("A2").Value2 = "John Smith" ' Write date to cell A3 in sheet1 of this workbook ThisWorkbook.Worksheets("Sheet1").Range("A3").Value2 = #11/21/2017# End Sub
As you can see Range is a member of the worksheet which in turn is a member of the Workbook. This follows the same hierarchy as in Excel so should be easy to understand. To do something with Range you must first specify the workbook and worksheet it belongs to.
For the rest of this post I will use the code name to reference the worksheet.
The following code shows the above example using the code name of the worksheet i.e. Sheet1 instead of ThisWorkbook.Worksheets(“Sheet1”).
' https://excelmacromastery.com/ Public Sub UsingCodeName() ' Write number to cell A1 in sheet1 of this workbook Sheet1.Range("A1").Value2 = 67 ' Write text to cell A2 in sheet1 of this workbook Sheet1.Range("A2").Value2 = "John Smith" ' Write date to cell A3 in sheet1 of this workbook Sheet1.Range("A3").Value2 = #11/21/2017# End Sub
You can also write to multiple cells using the Range property
' https://excelmacromastery.com/ Public Sub WriteToMulti() ' Write number to a range of cells Sheet1.Range("A1:A10").Value2 = 67 ' Write text to multiple ranges of cells Sheet1.Range("B2:B5,B7:B9").Value2 = "John Smith" End Sub
You can download working examples of all the code from this post from the top of this article.
The Cells Property of the Worksheet
The worksheet object has another property called Cells which is very similar to range. There are two differences
- Cells returns a range of one cell only.
- Cells takes row and column as arguments.
The example below shows you how to write values to cells using both the Range and Cells property
' https://excelmacromastery.com/ Public Sub UsingCells() ' Write to A1 Sheet1.Range("A1").Value2 = 10 Sheet1.Cells(1, 1).Value2 = 10 ' Write to A10 Sheet1.Range("A10").Value2 = 10 Sheet1.Cells(10, 1).Value2 = 10 ' Write to E1 Sheet1.Range("E1").Value2 = 10 Sheet1.Cells(1, 5).Value2 = 10 End Sub
You may be wondering when you should use Cells and when you should use Range. Using Range is useful for accessing the same cells each time the Macro runs.
For example, if you were using a Macro to calculate a total and write it to cell A10 every time then Range would be suitable for this task.
Using the Cells property is useful if you are accessing a cell based on a number that may vary. It is easier to explain this with an example.
In the following code, we ask the user to specify the column number. Using Cells gives us the flexibility to use a variable number for the column.
' https://excelmacromastery.com/ Public Sub WriteToColumn() Dim UserCol As Integer ' Get the column number from the user UserCol = Application.InputBox(" Please enter the column...", Type:=1) ' Write text to user selected column Sheet1.Cells(1, UserCol).Value2 = "John Smith" End Sub
In the above example, we are using a number for the column rather than a letter.
To use Range here would require us to convert these values to the letter/number cell reference e.g. “C1”. Using the Cells property allows us to provide a row and a column number to access a cell.
Sometimes you may want to return more than one cell using row and column numbers. The next section shows you how to do this.
Using Cells and Range together
As you have seen you can only access one cell using the Cells property. If you want to return a range of cells then you can use Cells with Ranges as follows
' https://excelmacromastery.com/ Public Sub UsingCellsWithRange() With Sheet1 ' Write 5 to Range A1:A10 using Cells property .Range(.Cells(1, 1), .Cells(10, 1)).Value2 = 5 ' Format Range B1:Z1 to be bold .Range(.Cells(1, 2), .Cells(1, 26)).Font.Bold = True End With End Sub
As you can see, you provide the start and end cell of the Range. Sometimes it can be tricky to see which range you are dealing with when the value are all numbers. Range has a property called Address which displays the letter/ number cell reference of any range. This can come in very handy when you are debugging or writing code for the first time.
In the following example we print out the address of the ranges we are using:
' https://excelmacromastery.com/ Public Sub ShowRangeAddress() ' Note: Using underscore allows you to split up lines of code With Sheet1 ' Write 5 to Range A1:A10 using Cells property .Range(.Cells(1, 1), .Cells(10, 1)).Value2 = 5 Debug.Print "First address is : " _ + .Range(.Cells(1, 1), .Cells(10, 1)).Address ' Format Range B1:Z1 to be bold .Range(.Cells(1, 2), .Cells(1, 26)).Font.Bold = True Debug.Print "Second address is : " _ + .Range(.Cells(1, 2), .Cells(1, 26)).Address End With End Sub
In the example I used Debug.Print to print to the Immediate Window. To view this window select View->Immediate Window(or Ctrl G)
You can download all the code for this post from the top of this article.
The Offset Property of Range
Range has a property called Offset. The term Offset refers to a count from the original position. It is used a lot in certain areas of programming. With the Offset property you can get a Range of cells the same size and a certain distance from the current range. The reason this is useful is that sometimes you may want to select a Range based on a certain condition. For example in the screenshot below there is a column for each day of the week. Given the day number(i.e. Monday=1, Tuesday=2 etc.) we need to write the value to the correct column.
We will first attempt to do this without using Offset.
' https://excelmacromastery.com/ ' This sub tests with different values Public Sub TestSelect() ' Monday SetValueSelect 1, 111.21 ' Wednesday SetValueSelect 3, 456.99 ' Friday SetValueSelect 5, 432.25 ' Sunday SetValueSelect 7, 710.17 End Sub ' Writes the value to a column based on the day Public Sub SetValueSelect(lDay As Long, lValue As Currency) Select Case lDay Case 1: Sheet1.Range("H3").Value2 = lValue Case 2: Sheet1.Range("I3").Value2 = lValue Case 3: Sheet1.Range("J3").Value2 = lValue Case 4: Sheet1.Range("K3").Value2 = lValue Case 5: Sheet1.Range("L3").Value2 = lValue Case 6: Sheet1.Range("M3").Value2 = lValue Case 7: Sheet1.Range("N3").Value2 = lValue End Select End Sub
As you can see in the example, we need to add a line for each possible option. This is not an ideal situation. Using the Offset Property provides a much cleaner solution
' https://excelmacromastery.com/ ' This sub tests with different values Public Sub TestOffset() DayOffSet 1, 111.01 DayOffSet 3, 456.99 DayOffSet 5, 432.25 DayOffSet 7, 710.17 End Sub Public Sub DayOffSet(lDay As Long, lValue As Currency) ' We use the day value with offset specify the correct column Sheet1.Range("G3").Offset(, lDay).Value2 = lValue End Sub
As you can see this solution is much better. If the number of days in increased then we do not need to add any more code. For Offset to be useful there needs to be some kind of relationship between the positions of the cells. If the Day columns in the above example were random then we could not use Offset. We would have to use the first solution.
One thing to keep in mind is that Offset retains the size of the range. So .Range(“A1:A3”).Offset(1,1) returns the range B2:B4. Below are some more examples of using Offset
' https://excelmacromastery.com/ Public Sub UsingOffset() ' Write to B2 - no offset Sheet1.Range("B2").Offset().Value2 = "Cell B2" ' Write to C2 - 1 column to the right Sheet1.Range("B2").Offset(, 1).Value2 = "Cell C2" ' Write to B3 - 1 row down Sheet1.Range("B2").Offset(1).Value2 = "Cell B3" ' Write to C3 - 1 column right and 1 row down Sheet1.Range("B2").Offset(1, 1).Value2 = "Cell C3" ' Write to A1 - 1 column left and 1 row up Sheet1.Range("B2").Offset(-1, -1).Value2 = "Cell A1" ' Write to range E3:G13 - 1 column right and 1 row down Sheet1.Range("D2:F12").Offset(1, 1).Value2 = "Cells E3:G13" End Sub
Using the Range CurrentRegion
CurrentRegion returns a range of all the adjacent cells to the given range.
In the screenshot below you can see the two current regions. I have added borders to make the current regions clear.
A row or column of blank cells signifies the end of a current region.
You can manually check the CurrentRegion in Excel by selecting a range and pressing Ctrl + Shift + *.
If we take any range of cells within the border and apply CurrentRegion, we will get back the range of cells in the entire area.
For example
Range(“B3”).CurrentRegion will return the range B3:D14
Range(“D14”).CurrentRegion will return the range B3:D14
Range(“C8:C9”).CurrentRegion will return the range B3:D14
and so on
How to Use
We get the CurrentRegion as follows
' Current region will return B3:D14 from above example Dim rg As Range Set rg = Sheet1.Range("B3").CurrentRegion
Read Data Rows Only
Read through the range from the second row i.e.skipping the header row
' Current region will return B3:D14 from above example Dim rg As Range Set rg = Sheet1.Range("B3").CurrentRegion ' Start at row 2 - row after header Dim i As Long For i = 2 To rg.Rows.Count ' current row, column 1 of range Debug.Print rg.Cells(i, 1).Value2 Next i
Remove Header
Remove header row(i.e. first row) from the range. For example if range is A1:D4 this will return A2:D4
' Current region will return B3:D14 from above example Dim rg As Range Set rg = Sheet1.Range("B3").CurrentRegion ' Remove Header Set rg = rg.Resize(rg.Rows.Count - 1).Offset(1) ' Start at row 1 as no header row Dim i As Long For i = 1 To rg.Rows.Count ' current row, column 1 of range Debug.Print rg.Cells(i, 1).Value2 Next i
Using Rows and Columns as Ranges
If you want to do something with an entire Row or Column you can use the Rows or Columns property of the Worksheet. They both take one parameter which is the row or column number you wish to access
' https://excelmacromastery.com/ Public Sub UseRowAndColumns() ' Set the font size of column B to 9 Sheet1.Columns(2).Font.Size = 9 ' Set the width of columns D to F Sheet1.Columns("D:F").ColumnWidth = 4 ' Set the font size of row 5 to 18 Sheet1.Rows(5).Font.Size = 18 End Sub
Using Range in place of Worksheet
You can also use Cells, Rows and Columns as part of a Range rather than part of a Worksheet. You may have a specific need to do this but otherwise I would avoid the practice. It makes the code more complex. Simple code is your friend. It reduces the possibility of errors.
The code below will set the second column of the range to bold. As the range has only two rows the entire column is considered B1:B2
' https://excelmacromastery.com/ Public Sub UseColumnsInRange() ' This will set B1 and B2 to be bold Sheet1.Range("A1:C2").Columns(2).Font.Bold = True End Sub
You can download all the code for this post from the top of this article.
Reading Values from one Cell to another
In most of the examples so far we have written values to a cell. We do this by placing the range on the left of the equals sign and the value to place in the cell on the right. To write data from one cell to another we do the same. The destination range goes on the left and the source range goes on the right.
The following example shows you how to do this:
' https://excelmacromastery.com/ Public Sub ReadValues() ' Place value from B1 in A1 Sheet1.Range("A1").Value2 = Sheet1.Range("B1").Value2 ' Place value from B3 in sheet2 to cell A1 Sheet1.Range("A1").Value2 = Sheet2.Range("B3").Value2 ' Place value from B1 in cells A1 to A5 Sheet1.Range("A1:A5").Value2 = Sheet1.Range("B1").Value2 ' You need to use the "Value" property to read multiple cells Sheet1.Range("A1:A5").Value2 = Sheet1.Range("B1:B5").Value2 End Sub
As you can see from this example it is not possible to read from multiple cells. If you want to do this you can use the Copy function of Range with the Destination parameter
' https://excelmacromastery.com/ Public Sub CopyValues() ' Store the copy range in a variable Dim rgCopy As Range Set rgCopy = Sheet1.Range("B1:B5") ' Use this to copy from more than one cell rgCopy.Copy Destination:=Sheet1.Range("A1:A5") ' You can paste to multiple destinations rgCopy.Copy Destination:=Sheet1.Range("A1:A5,C2:C6") End Sub
The Copy function copies everything including the format of the cells. It is the same result as manually copying and pasting a selection. You can see more about it in the Copying and Pasting Cells section.
Using the Range.Resize Method
When copying from one range to another using assignment(i.e. the equals sign), the destination range must be the same size as the source range.
Using the Resize function allows us to resize a range to a given number of rows and columns.
For example:
' https://excelmacromastery.com/ Sub ResizeExamples() ' Prints A1 Debug.Print Sheet1.Range("A1").Address ' Prints A1:A2 Debug.Print Sheet1.Range("A1").Resize(2, 1).Address ' Prints A1:A5 Debug.Print Sheet1.Range("A1").Resize(5, 1).Address ' Prints A1:D1 Debug.Print Sheet1.Range("A1").Resize(1, 4).Address ' Prints A1:C3 Debug.Print Sheet1.Range("A1").Resize(3, 3).Address End Sub
When we want to resize our destination range we can simply use the source range size.
In other words, we use the row and column count of the source range as the parameters for resizing:
' https://excelmacromastery.com/ Sub Resize() Dim rgSrc As Range, rgDest As Range ' Get all the data in the current region Set rgSrc = Sheet1.Range("A1").CurrentRegion ' Get the range destination Set rgDest = Sheet2.Range("A1") Set rgDest = rgDest.Resize(rgSrc.Rows.Count, rgSrc.Columns.Count) rgDest.Value2 = rgSrc.Value2 End Sub
We can do the resize in one line if we prefer:
' https://excelmacromastery.com/ Sub ResizeOneLine() Dim rgSrc As Range ' Get all the data in the current region Set rgSrc = Sheet1.Range("A1").CurrentRegion With rgSrc Sheet2.Range("A1").Resize(.Rows.Count, .Columns.Count).Value2 = .Value2 End With End Sub
Reading Values to variables
We looked at how to read from one cell to another. You can also read from a cell to a variable. A variable is used to store values while a Macro is running. You normally do this when you want to manipulate the data before writing it somewhere. The following is a simple example using a variable. As you can see the value of the item to the right of the equals is written to the item to the left of the equals.
' https://excelmacromastery.com/ Public Sub UseVariables() ' Create Dim number As Long ' Read number from cell number = Sheet1.Range("A1").Value2 ' Add 1 to value number = number + 1 ' Write new value to cell Sheet1.Range("A2").Value2 = number End Sub
To read text to a variable you use a variable of type String:
' https://excelmacromastery.com/ Public Sub UseVariableText() ' Declare a variable of type string Dim text As String ' Read value from cell text = Sheet1.Range("A1").Value2 ' Write value to cell Sheet1.Range("A2").Value2 = text End Sub
You can write a variable to a range of cells. You just specify the range on the left and the value will be written to all cells in the range.
' https://excelmacromastery.com/ Public Sub VarToMulti() ' Read value from cell Sheet1.Range("A1:B10").Value2 = 66 End Sub
You cannot read from multiple cells to a variable. However you can read to an array which is a collection of variables. We will look at doing this in the next section.
How to Copy and Paste Cells
If you want to copy and paste a range of cells then you do not need to select them. This is a common error made by new VBA users.
Note: We normally use Range.Copy when we want to copy formats, formulas, validation. If we want to copy values it is not the most efficient method.
I have written a complete guide to copying data in Excel VBA here.
You can simply copy a range of cells like this:
Range("A1:B4").Copy Destination:=Range("C5")
Using this method copies everything – values, formats, formulas and so on. If you want to copy individual items you can use the PasteSpecial property of range.
It works like this
Range("A1:B4").Copy Range("F3").PasteSpecial Paste:=xlPasteValues Range("F3").PasteSpecial Paste:=xlPasteFormats Range("F3").PasteSpecial Paste:=xlPasteFormulas
The following table shows a full list of all the paste types
Paste Type |
---|
xlPasteAll |
xlPasteAllExceptBorders |
xlPasteAllMergingConditionalFormats |
xlPasteAllUsingSourceTheme |
xlPasteColumnWidths |
xlPasteComments |
xlPasteFormats |
xlPasteFormulas |
xlPasteFormulasAndNumberFormats |
xlPasteValidation |
xlPasteValues |
xlPasteValuesAndNumberFormats |
Reading a Range of Cells to an Array
You can also copy values by assigning the value of one range to another.
Range("A3:Z3").Value2 = Range("A1:Z1").Value2
The value of range in this example is considered to be a variant array. What this means is that you can easily read from a range of cells to an array. You can also write from an array to a range of cells. If you are not familiar with arrays you can check them out in this post.
The following code shows an example of using an array with a range:
' https://excelmacromastery.com/ Public Sub ReadToArray() ' Create dynamic array Dim StudentMarks() As Variant ' Read 26 values into array from the first row StudentMarks = Range("A1:Z1").Value2 ' Do something with array here ' Write the 26 values to the third row Range("A3:Z3").Value2 = StudentMarks End Sub
Keep in mind that the array created by the read is a 2 dimensional array. This is because a spreadsheet stores values in two dimensions i.e. rows and columns
Going through all the cells in a Range
Sometimes you may want to go through each cell one at a time to check value.
You can do this using a For Each loop shown in the following code
' https://excelmacromastery.com/ Public Sub TraversingCells() ' Go through each cells in the range Dim rg As Range For Each rg In Sheet1.Range("A1:A10,A20") ' Print address of cells that are negative If rg.Value < 0 Then Debug.Print rg.Address + " is negative." End If Next End Sub
You can also go through consecutive Cells using the Cells property and a standard For loop.
The standard loop is more flexible about the order you use but it is slower than a For Each loop.
' https://excelmacromastery.com/ Public Sub TraverseCells() ' Go through cells from A1 to A10 Dim i As Long For i = 1 To 10 ' Print address of cells that are negative If Range("A" & i).Value < 0 Then Debug.Print Range("A" & i).Address + " is negative." End If Next ' Go through cells in reverse i.e. from A10 to A1 For i = 10 To 1 Step -1 ' Print address of cells that are negative If Range("A" & i) < 0 Then Debug.Print Range("A" & i).Address + " is negative." End If Next End Sub
Formatting Cells
Sometimes you will need to format the cells the in spreadsheet. This is actually very straightforward. The following example shows you various formatting you can add to any range of cells
' https://excelmacromastery.com/ Public Sub FormattingCells() With Sheet1 ' Format the font .Range("A1").Font.Bold = True .Range("A1").Font.Underline = True .Range("A1").Font.Color = rgbNavy ' Set the number format to 2 decimal places .Range("B2").NumberFormat = "0.00" ' Set the number format to a date .Range("C2").NumberFormat = "dd/mm/yyyy" ' Set the number format to general .Range("C3").NumberFormat = "General" ' Set the number format to text .Range("C4").NumberFormat = "Text" ' Set the fill color of the cell .Range("B3").Interior.Color = rgbSandyBrown ' Format the borders .Range("B4").Borders.LineStyle = xlDash .Range("B4").Borders.Color = rgbBlueViolet End With End Sub
Main Points
The following is a summary of the main points
- Range returns a range of cells
- Cells returns one cells only
- You can read from one cell to another
- You can read from a range of cells to another range of cells.
- You can read values from cells to variables and vice versa.
- You can read values from ranges to arrays and vice versa
- You can use a For Each or For loop to run through every cell in a range.
- The properties Rows and Columns allow you to access a range of cells of these types
What’s Next?
Free VBA Tutorial If you are new to VBA or you want to sharpen your existing VBA skills then why not try out the The Ultimate VBA Tutorial.
Related Training: Get full access to the Excel VBA training webinars and all the tutorials.
(NOTE: Planning to build or manage a VBA Application? Learn how to build 10 Excel VBA applications from scratch.)
Свойства Column и Columns объекта Range в VBA Excel. Возвращение номера первого столбца и обращение к столбцам смежных и несмежных диапазонов.
Range.Column — свойство, которое возвращает номер первого столбца в указанном диапазоне.
Свойство Column объекта Range предназначено только для чтения, тип данных — Long.
Если диапазон состоит из нескольких областей (несмежный диапазон), свойство Range.Column возвращает номер первого столбца в первой области указанного диапазона:
Range(«B2:F10»).Select MsgBox Selection.Column ‘Результат: 2 Range(«E1:F8,D4:G13,B2:F10»).Select MsgBox Selection.Column ‘Результат: 5 |
Для возвращения номеров первых столбцов отдельных областей несмежного диапазона используется свойство Areas объекта Range:
Range(«E1:F8,D4:G13,B2:F10»).Select MsgBox Selection.Areas(1).Column ‘Результат: 5 MsgBox Selection.Areas(2).Column ‘Результат: 4 MsgBox Selection.Areas(3).Column ‘Результат: 2 |
Свойство Range.Columns
Range.Columns — свойство, которое возвращает объект Range, представляющий коллекцию столбцов в указанном диапазоне.
Чтобы возвратить один столбец заданного диапазона, необходимо указать его порядковый номер (индекс) в скобках:
Set myRange = Range(«B4:D6»).Columns(1) ‘Возвращается диапазон: $B$4:$B$6 Set myRange = Range(«B4:D6»).Columns(2) ‘Возвращается диапазон: $C$4:$C$6 Set myRange = Range(«B4:D6»).Columns(3) ‘Возвращается диапазон: $D$4:$D$6 |
Самое удивительное заключается в том, что выход индекса столбца за пределы указанного диапазона не приводит к ошибке, а возвращается диапазон, расположенный за пределами исходного диапазона (отсчет начинается с первого столбца заданного диапазона):
MsgBox Range(«B4:D6»).Columns(7).Address ‘Результат: $H$4:$H$6 |
Если указанный объект Range является несмежным, состоящим из нескольких смежных диапазонов (областей), свойство Columns возвращает коллекцию столбцов первой области заданного диапазона. Для обращения к столбцам других областей указанного диапазона используется свойство Areas объекта Range:
Range(«E1:F8,D4:G13,B2:F10»).Select MsgBox Selection.Areas(1).Columns(2).Address ‘Результат: $F$1:$F$8 MsgBox Selection.Areas(2).Columns(2).Address ‘Результат: $E$4:$E$13 MsgBox Selection.Areas(3).Columns(2).Address ‘Результат: $C$2:$C$10 |
Определение количества столбцов в диапазоне:
Dim c As Long c = Range(«D5:J11»).Columns.Count MsgBox c ‘Результат: 7 |
Буква вместо номера
Если в качестве индекса столбца используется буква, она соответствует порядковому номеру этой буквы на рабочем листе:
"A" = 1;
"B" = 2;
"C" = 3;
и так далее.
Пример использования буквенного индекса вместо номера столбца в качестве аргумента свойства Columns объекта Range:
Range(«G2:K10»).Select MsgBox Selection.Columns(2).Address ‘Результат: $H$2:$H$10 MsgBox Selection.Columns(«B»).Address ‘Результат: $H$2:$H$10 |
Обратите внимание, что свойство Range("G2:K10").Columns("B")
возвращает диапазон $H$2:$H$10
, а не $B$2:$B$10
.
Home / VBA / VBA Insert Column (Single and Multiple)
In this tutorial, we will look at how to insert a column using a VBA code in Excel. We will also explore what are the different ways to write a macro for this.
To insert a column using a VBA code, you need to use the “Entire Column” property with the “Insert” method. With the entire column property, you can refer to the entire column using a cell and then insert a new column. By default, it will insert a column before the cell that you have mentioned.
- First, specify a cell using the range object.
- Now, enter a dot (.) to get the list of properties and methods.
- After that, select the “Entire Column” property or type it.
- In the end, again enter a dot (.) and select the “Insert” method or type it.
Range("A1").EntireColumn.Insert
Your code is ready here to insert a column. Now when you run this code, it will instantly insert a new column before the column A.
Insert Multiple Columns
There are two ways to insert multiple columns in a worksheet that I have found. The first is the same insert method that we have used in the above example. With this, you need to specify a range of columns whose count is equal to the count of the column you want to insert.
Now let’s say you want to insert 5 columns after column C in the case you can use a code like the following.
Range("C:G").EntireColumn.Insert
To be honest, I haven’t found this method quite useful because you need to change the range if you want to change the code itself. So, here’s the second method.
'variables to use in the code
Dim iCol As Long
Dim iCount As Long
Dim i As Long
'to get the number of columns that you want to insert with an input box
iCount = InputBox(Prompt:="How many column you want to add?")
'to get the column number where you want to insert the new column
iCol = InputBox _
(Prompt:= _
"After which column you want to add new column? (Enter the column number)")
'loop to insert new column(s)
For i = 1 To iCount
Columns(iCol).EntireColumn.Insert
Next i
When you run this code, it asks you to enter the number of columns that you want to add and then the column number where you want to add all those new columns. It uses a FOR LOOP (For Next) to enter the number of columns that you have mentioned.
Insert Columns Based on the Cell Values
If you want to insert columns based on a cell value, then you can use the following code.
Dim iCol As Long
Dim iCount As Long
Dim i As Long
iCount = Range("A1").Value
iCol = Range("B1").Value
For i = 1 To iCount
Columns(iCol).EntireColumn.Insert
Next i
When you run this macro, it takes count of columns from the cell A1 and the column where you want to add columns from the cell B1.
Insert a Column without Formatting
When you insert a column where the above column has some specific formatting, in that case, the column will also have that formatting automatically. And the simplest way to deal with this thing is to use clear formats. Consider the following code.
Columns(7).EntireColumn.Insert
Columns(7).ClearFormats
When you run the above code, it inserts a new column before the 7th column. Now, what happens, when you insert a column before the 7th column that new column becomes the 7th column, and then the second line of code clear the formats from it.
Insert Copied Column
You can also use the same method to copy a column and then insert it somewhere else. See the following code.
Application.CutCopyMode = False
With Worksheets("Data")
.Columns(5).Copy
.Columns(9).Insert Shift:=xlShiftDown
End With
Application.CutCopyMode = True
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 a Range/Cell using VBA in Excel
- 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 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
The VBA Range Object
The Excel Range Object is an object in Excel VBA that represents a cell, row, column, a selection of cells or a 3 dimensional range. The Excel Range is also a Worksheet property that returns a subset of its cells.
Worksheet Range
The Range is a Worksheet property which allows you to select any subset of cells, rows, columns etc.
Dim r as Range 'Declared Range variable Set r = Range("A1") 'Range of A1 cell Set r = Range("A1:B2") 'Square Range of 4 cells - A1,A2,B1,B2 Set r= Range(Range("A1"), Range ("B1")) 'Range of 2 cells A1 and B1 Range("A1:B2").Select 'Select the Cells A1:B2 in your Excel Worksheet Range("A1:B2").Activate 'Activate the cells and show them on your screen (will switch to Worksheet and/or scroll to this range.
Select a cell or Range of cells using the Select method. It will be visibly marked in Excel:
Working with Range variables
The Range is a separate object variable and can be declared as other variables. As the VBA Range is an object you need to use the Set statement:
Dim myRange as Range '... Set myRange = Range("A1") 'Need to use Set to define myRange
The Range object defaults to your ActiveWorksheet. So beware as depending on your ActiveWorksheet the Range object will return values local to your worksheet:
Range("A1").Select '...is the same as... ActiveSheet.Range("A1").Select
You might want to define the Worksheet reference by Range if you want your reference values from a specifc Worksheet:
Sheets("Sheet1").Range("A1").Select 'Will always select items from Worksheet named Sheet1
The ActiveWorkbook is not same to ThisWorkbook. Same goes for the ActiveSheet. This may reference a Worksheet from within a Workbook external to the Workbook in which the macro is executed as Active references simply the currently top-most worksheet. Read more here
Range properties
The Range object contains a variety of properties with the main one being it’s Value and an the second one being its Formula.
A Range Value is the evaluated property of a cell or a range of cells. For example a cell with the formula =10+20
has an evaluated value of 20
.
A Range Formula is the formula provided in the cell or range of cells. For example a cell with a formula of =10+20
will have the same Formula property.
'Let us assume A1 contains the formula "=10+20" Debug.Print Range("A1").Value 'Returns: 30 Debug.Print Range("A1").Formula 'Returns: =10+20
Other Range properties include:
Work in progress
Worksheet Cells
A Worksheet Cells property is similar to the Range property but allows you to obtain only a SINGLE CELL, based on its row and column index. Numbering starts at 1:
The Cells property is in fact a Range object not a separate data type.
Excel facilitates a Cells function that allows you to obtain a cell from within the ActiveSheet, current top-most worksheet.
Cells(2,2).Select 'Selects B2 '...is the same as... ActiveSheet.Cells(2,2).Select 'Select B2
Cells are Ranges which means they are not a separate data type:
Dim myRange as Range Set myRange = Cells(1,1) 'Cell A1
Range Rows and Columns
As we all know an Excel Worksheet is divided into Rows and Columns. The Excel VBA Range object allows you to select single or multiple rows as well as single or multiple columns. There are a couple of ways to obtain Worksheet rows in VBA:
Getting an entire row or column
To get and entire row of a specified Range you need to use the EntireRow property. Although, the function’s parameters suggest taking both a RowIndex and ColumnIndex it is enough just to provide the row number. Row indexing starts at 1.
To get and entire column of a specified Range you need to use the EntireColumn property. Although, the function’s parameters suggest taking both a RowIndex and ColumnIndex it is enough just to provide the column number. Column indexing starts at 1.
Range("B2").EntireRows(1).Hidden = True 'Gets and hides the entire row 2 Range("B2").EntireColumns(1).Hidden = True 'Gets and hides the entire column 2
The three properties EntireRow/EntireColumn, Rows/Columns and Row/Column are often misunderstood so read through to understand the differences.
Get a row/column of a specified range
If you want to get a certain row within a Range simply use the Rows property of the Worksheet. Although, the function’s parameters suggest taking both a RowIndex and ColumnIndex it is enough just to provide the row number. Row indexing starts at 1.
Similarly you can use the Columns function to obtain any single column within a Range. Although, the function’s parameters suggest taking both a RowIndex and ColumnIndex actually the first argument you provide will be the column index. Column indexing starts at 1.
Rows(1).Hidden = True 'Hides the first row in the ActiveSheet 'same as ActiveSheet.Rows(1).Hidden = True Columns(1).Hidden = True 'Hides the first column in the ActiveSheet 'same as ActiveSheet.Columns(1).Hidden = True
To get a range of rows/columns you need to use the Range function like so:
Range(Rows(1), Rows(3)).Hidden = True 'Hides rows 1:3 'same as Range("1:3").Hidden = True 'same as ActiveSheet.Range("1:3").Hidden = True Range(Columns(1), Columns(3)).Hidden = True 'Hides columns A:C 'same as Range("A:C").Hidden = True 'same as ActiveSheet.Range("A:C").Hidden = True
Get row/column of specified range
The above approach assumed you want to obtain only rows/columns from the ActiveSheet – the visible and top-most Worksheet. Usually however, you will want to obtain rows or columns of an existing Range. Similarly as with the Worksheet Range property, any Range facilitates the Rows and Columns property.
Dim myRange as Range Set myRange = Range("A1:C3") myRange.Rows.Hidden = True 'Hides rows 1:3 myRange.Columns.Hidden = True 'Hides columns A:C Set myRange = Range("C10:F20") myRange.Rows(2).Hidden = True 'Hides rows 11 myRange.Columns(3).Hidden = True 'Hides columns E
Getting a Ranges first row/column number
Aside from the Rows and Columns properties Ranges also facilitate a Row and Column property which provide you with the number of the Ranges first row and column.
Set myRange = Range("C10:F20") 'Get first row number Debug.Print myRange.Row 'Result: 10 'Get first column number Debug.Print myRange.Column 'Result: 3
Converting Column number to Excel Column
This is an often question that turns up – how to convert a column number to a string e.g. 100 to “CV”.
Function GetExcelColumn(columnNumber As Long) Dim div As Long, colName As String, modulo As Long div = columnNumber: colName = vbNullString Do While div > 0 modulo = (div - 1) Mod 26 colName = Chr(65 + modulo) & colName div = ((div - modulo) / 26) Loop GetExcelColumn = colName End Function
Range Cut/Copy/Paste
Cutting and pasting rows is generally a bad practice which I heavily discourage as this is a practice that is moments can be heavily cpu-intensive and often is unaccounted for.
Copy function
The Copy function works on a single cell, subset of cell or subset of rows/columns.
'Copy values and formatting from cell A1 to cell D1 Range("A1").Copy Range("D1") 'Copy 3x3 A1:C3 matrix to D1:F3 matrix - dimension must be same Range("A1:C3").Copy Range("D1:F3") 'Copy rows 1:3 to rows 4:6 Range("A1:A3").EntireRow.Copy Range("A4") 'Copy columns A:C to columns D:F Range("A1:C1").EntireColumn.Copy Range("D1")
The Copy function can also be executed without an argument. It then copies the Range to the Windows Clipboard for later Pasting.
Cut function
The Cut function, similarly as the Copy function, cuts single cells, ranges of cells or rows/columns.
'Cut A1 cell and paste it to D1 Range("A1").Cut Range("D1") 'Cut 3x3 A1:C3 matrix and paste it in D1:F3 matrix - dimension must be same Range("A1:C3").Cut Range("D1:F3") 'Cut rows 1:3 and paste to rows 4:6 Range("A1:A3").EntireRow.Cut Range("A4") 'Cut columns A:C and paste to columns D:F Range("A1:C1").EntireColumn.Cut Range("D1")
The Cut function can be executed without arguments. It will then cut the contents of the Range and copy it to the Windows Clipboard for pasting.
Cutting cells/rows/columns does not shift any remaining cells/rows/columns but simply leaves the cut out cells empty
PasteSpecial function
The Range PasteSpecial function works only when preceded with either the Copy or Cut Range functions. It pastes the Range (or other data) within the Clipboard to the Range on which it was executed.
Syntax
The PasteSpecial function has the following syntax:
PasteSpecial( Paste, Operation, SkipBlanks, Transpose)
The PasteSpecial function can only be used in tandem with the Copy function (not Cut)
Parameters
Paste
The part of the Range which is to be pasted. This parameter can have the following values:
Parameter | Constant | Description | |
---|---|---|---|
xlPasteSpecialOperationAdd | 2 | Copied data will be added with the value in the destination cell. | |
xlPasteSpecialOperationDivide | 5 | Copied data will be divided with the value in the destination cell. | |
xlPasteSpecialOperationMultiply | 4 | Copied data will be multiplied with the value in the destination cell. | |
xlPasteSpecialOperationNone | -4142 | No calculation will be done in the paste operation. | |
xlPasteSpecialOperationSubtract | 3 | Copied data will be subtracted with the value in the destination cell. |
Operation
The paste operation e.g. paste all, only formatting, only values, etc. This can have one of the following values:
Name | Constant | Description |
---|---|---|
xlPasteAll | -4104 | Everything will be pasted. |
xlPasteAllExceptBorders | 7 | Everything except borders will be pasted. |
xlPasteAllMergingConditionalFormats | 14 | Everything will be pasted and conditional formats will be merged. |
xlPasteAllUsingSourceTheme | 13 | Everything will be pasted using the source theme. |
xlPasteColumnWidths | 8 | Copied column width is pasted. |
xlPasteComments | -4144 | Comments are pasted. |
xlPasteFormats | -4122 | Copied source format is pasted. |
xlPasteFormulas | -4123 | Formulas are pasted. |
xlPasteFormulasAndNumberFormats | 11 | Formulas and Number formats are pasted. |
xlPasteValidation | 6 | Validations are pasted. |
xlPasteValues | -4163 | Values are pasted. |
xlPasteValuesAndNumberFormats | 12 | Values and Number formats are pasted. |
SkipBlanks
If True then blanks will not be pasted.
Transpose
Transpose the Range before paste (swap rows with columns).
PasteSpecial Examples
'Cut A1 cell and paste its values to D1 Range("A1").Copy Range("D1").PasteSpecial 'Copy 3x3 A1:C3 matrix and add all the values to E1:G3 matrix (dimension must be same) Range("A1:C3").Copy Range("E1:G3").PasteSpecial xlPasteValues, xlPasteSpecialOperationAdd
Below an example where the Excel Range A1:C3 values are copied an added to the E1:G3 Range. You can also multiply, divide and run other similar operations.
Paste
The Paste function allows you to paste data in the Clipboard to the actively selected Range. Cutting and Pasting can only be accomplished with the Paste function.
'Cut A1 cell and paste its values to D1 Range("A1").Cut Range("D1").Select ActiveSheet.Paste 'Cut 3x3 A1:C3 matrix and paste it in D1:F3 matrix - dimension must be same Range("A1:C3").Cut Range("D1:F3").Select ActiveSheet.Paste 'Cut rows 1:3 and paste to rows 4:6 Range("A1:A3").EntireRow.Cut Range("A4").Select ActiveSheet.Paste 'Cut columns A:C and paste to columns D:F Range("A1:C1").EntireColumn.Cut Range("D1").Select ActiveSheet.Paste
Range Clear/Delete
The Clear function
The Clear function clears the entire content and formatting from an Excel Range. It does not, however, shift (delete) the cleared cells.
Range("A1:C3").Clear
The Delete function
The Delete function deletes a Range of cells, removing them entirely from the Worksheet, and shifts the remaining Cells in a selected shift direction.
Although the manual Delete cell function provides 4 ways of shifting cells. The VBA Delete Shift values can only be either be xlShiftToLeft or xlShiftUp.
'If Shift omitted, Excel decides - shift up in this case Range("B2").Delete 'Delete and Shift remaining cells left Range("B2").Delete xlShiftToLeft 'Delete and Shift remaining cells up Range("B2").Delete xlShiftTop 'Delete entire row 2 and shift up Range("B2").EntireRow.Delete 'Delete entire column B and shift left Range("B2").EntireRow.Delete
Traversing Ranges
Traversing cells is really useful when you want to run an operation on each cell within an Excel Range. Fortunately this is easily achieved in VBA using the For Each or For loops.
Dim cellRange As Range For Each cellRange In Range("A1:C3") Debug.Print cellRange.Value Next cellRange
Although this may not be obvious, beware of iterating/traversing the Excel Range using a simple For loop. For loops are not efficient on Ranges. Use a For Each loop as shown above. This is because Ranges resemble more Collections than Arrays. Read more on For vs For Each loops here
Traversing the UsedRange
Every Worksheet has a UsedRange. This represents that smallest rectangle Range that contains all cells that have or had at some point values. In other words if the further out in the bottom, right-corner of the Worksheet there is a certain cell (e.g. E8) then the UsedRange will be as large as to include that cell starting at cell A1 (e.g. A1:E8). In Excel you can check the current UsedRange hitting CTRL+END. In VBA you get the UsedRange like this:
ActiveSheet.UsedRange 'same as UsedRange
You can traverse through the UsedRange like this:
Dim cellRange As Range For Each cellRange In UsedRange Debug.Print "Row: " & cellRange.Row & ", Column: " & cellRange.Column Next cellRange
The UsedRange is a useful construct responsible often for bloated Excel Workbooks. Often delete unused Rows and Columns that are considered to be within the UsedRange can result in significantly reducing your file size. Read also more on the XSLB file format here
Range Addresses
The Excel Range Address property provides a string value representing the Address of the Range.
Syntax
Below the syntax of the Excel Range Address property:
Address( [RowAbsolute], [ColumnAbsolute], [ReferenceStyle], [External], [RelativeTo] )
Parameters
RowAbsolute
Optional. If True returns the row part of the reference address as an absolute reference. By default this is True.
$D$10:$G$100 'RowAbsolute is set to True $D10:$G100 'RowAbsolute is set to False
ColumnAbsolute
Optional. If True returns the column part of the reference as an absolute reference. By default this is True.
$D$10:$G$100 'ColumnAbsolute is set to True D$10:G$100 'ColumnAbsolute is set to False
ReferenceStyle
Optional. The reference style. The default value is xlA1. Possible values:
Constant | Value | Description |
---|---|---|
xlA1 | 1 | Default. Use xlA1 to return an A1-style reference |
xlR1C1 | -4150 | Use xlR1C1 to return an R1C1-style reference |
External
Optional. If True then property will return an external reference address, otherwise a local reference address will be returned. By default this is False.
$A$1 'Local [Book1.xlsb]Sheet1!$A$1 'External
RelativeTo
Provided RowAbsolute and ColumnAbsolute are set to False, and the ReferenceStyle is set to xlR1C1, then you must include a starting point for the relative reference. This must be a Range variable to be set as the reference point.
Merged Ranges
Merged cells are Ranges that consist of 2 or more adjacent cells. To Merge a collection of adjacent cells run Merge function on that Range.
The Merge has only a single parameter – Across, a boolean which if True will merge cells in each row of the specified range as separate merged cells. Otherwise the whole Range will be merged. The default value is False.
Merge examples
To merge the entire Range:
'This will turn of any alerts warning that values may be lost Application.DisplayAlerts = False Range("B2:C3").Merge
This will result in the following:
To merge just the rows set Across to True.
'This will turn of any alerts warning that values may be lost Application.DisplayAlerts = False Range("B2:C3").Merge True
This will result in the following:
Remember that merged Ranges can only have a single value and formula. Hence, if you merge a group of cells with more than a single value/formula only the first value/formula will be set as the value/formula for your new merged Range
Checking if Range is merged
To check if a certain Range is merged simply use the Excel Range MergeCells property:
Range("B2:C3").Merge Debug.Print Range("B2").MergeCells 'Result: True
The MergeArea
The MergeArea is a property of an Excel Range that represent the whole merge Range associated with the current Range. Say that $B$2:$C$3 is a merged Range – each cell within that Range (e.g. B2, C3..) will have the exact same MergedArea. See example below:
Range("B2:C3").Merge Debug.Print Range("B2").MergeArea.Address 'Result: $B$2:$C$3
Named Ranges
Named Ranges are Ranges associated with a certain Name (string). In Excel you can find all your Named Ranges by going to Formulas->Name Manager. They are very useful when working on certain values that are used frequently through out your Workbook. Imagine that you are writing a Financial Analysis and want to use a common Discount Rate across all formulas. Just the address of the cell e.g. “A2”, won’t be self-explanatory. Why not use e.g. “DiscountRate” instead? Well you can do just that.
Creating a Named Range
Named Ranges can be created either within the scope of a Workbook or Worksheet:
Dim r as Range 'Within Workbook Set r = ActiveWorkbook.Names.Add("NewName", Range("A1")) 'Within Worksheet Set r = ActiveSheet.Names.Add("NewName", Range("A1"))
This gives you flexibility to use similar names across multiple Worksheets or use a single global name across the entire Workbook.
Listing all Named Ranges
You can list all Named Ranges using the Name Excel data type. Names are objects that represent a single NamedRange. See an example below of listing our two newly created NamedRanges:
Call ActiveWorkbook.Names.Add("NewName", Range("A1")) Call ActiveSheet.Names.Add("NewName", Range("A1")) Dim n As Name For Each n In ActiveWorkbook.Names Debug.Print "Name: " & n.Name & ", Address: " & _ n.RefersToRange.Address & ", Value: "; n.RefersToRange.Value Next n 'Result: 'Name: Sheet1!NewName, Address: $A$1, Value: 1 'Name: NewName, Address: $A$1, Value: 1
SpecialCells
SpecialCells are a very useful Excel Range property, that allows you to select a subset of cells/Ranges within a certain Range.
Syntax
The SpecialCells property has the following syntax:
SpecialCells( Type, [Value] )
Parameters
Type
The type of cells to be returned. Possible values:
Constant | Value | Description |
---|---|---|
xlCellTypeAllFormatConditions | -4172 | Cells of any format |
xlCellTypeAllValidation | -4174 | Cells having validation criteria |
xlCellTypeBlanks | 4 | Empty cells |
xlCellTypeComments | -4144 | Cells containing notes |
xlCellTypeConstants | 2 | Cells containing constants |
xlCellTypeFormulas | -4123 | Cells containing formulas |
xlCellTypeLastCell | 11 | The last cell in the used range |
xlCellTypeSameFormatConditions | -4173 | Cells having the same format |
xlCellTypeSameValidation | -4175 | Cells having the same validation criteria |
xlCellTypeVisible | 12 | All visible cells |
Value
If Type is equal to xlCellTypeConstants or xlCellTypeFormulas this determines the types of cells to return e.g. with errors.
Constant | Value |
---|---|
xlErrors | 16 |
xlLogical | 4 |
xlNumbers | 1 |
xlTextValues | 2 |
SpecialCells examples
Get Excel Range with Constants
This will return only cells with constant cells within the Range C1:C3:
For Each r In Range("A1:C3").SpecialCells(xlCellTypeConstants) Debug.Print r.Value Next r
Search for Excel Range with Errors
For Each r In ActiveSheet.UsedRange.SpecialCells(xlCellTypeFormulas, xlErrors) Debug.Print r.Address Next r