“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.)
In this Article
- Select Entire Rows or Columns
- Select Single Row
- Select Single Column
- Select Multiple Rows or Columns
- Select ActiveCell Row or Column
- Select Rows and Columns on Other Worksheets
- Is Selecting Rows and Columns Necessary?
- Methods and Properties of Rows & Columns
- Delete Entire Rows or Columns
- Insert Rows or Columns
- Copy & Paste Entire Rows or Columns
- Hide / Unhide Rows and Columns
- Group / UnGroup Rows and Columns
- Set Row Height or Column Width
- Autofit Row Height / Column Width
- Rows and Columns on Other Worksheets or Workbooks
- Get Active Row or Column
This tutorial will demonstrate how to select and work with entire rows or columns in VBA.
First we will cover how to select entire rows and columns, then we will demonstrate how to manipulate rows and columns.
Select Entire Rows or Columns
Select Single Row
You can select an entire row with the Rows Object like this:
Rows(5).Select
Or you can use EntireRow along with the Range or Cells Objects:
Range("B5").EntireRow.Select
or
Cells(5,1).EntireRow.Select
You can also use the Range Object to refer specifically to a Row:
Range("5:5").Select
Select Single Column
Instead of the Rows Object, use the Columns Object to select columns. Here you can reference the column number 3:
Columns(3).Select
or letter “C”, surrounded by quotations:
Columns("C").Select
Instead of EntireRow, use EntireColumn along with the Range or Cells Objects to select entire columns:
Range("C5").EntireColumn.Select
or
Cells(5,3).EntireColumn.Select
You can also use the Range Object to refer specifically to a column:
Range("B:B").Select
Select Multiple Rows or Columns
Selecting multiple rows or columns works exactly the same when using EntireRow or EntireColumn:
Range("B5:D10").EntireRow.Select
or
Range("B5:B10").EntireColumn.Select
However, when you use the Rows or Columns Objects, you must enter the row numbers or column letters in quotations:
Rows("1:3").Select
or
Columns("B:C").Select
Select ActiveCell Row or Column
To select the ActiveCell Row or Column, you can use one of these lines of code:
ActiveCell.EntireRow.Select
or
ActiveCell.EntireColumn.Select
Select Rows and Columns on Other Worksheets
In order to select Rows or Columns on other worksheets, you must first select the worksheet.
Sheets("Sheet2").Select
Rows(3).Select
The same goes for when selecting rows or columns in other workbooks.
Workbooks("Book6.xlsm").Activate
Sheets("Sheet2").Select
Rows(3).Select
Note: You must Activate the desired workbook. Unlike the Sheets Object, the Workbook Object does not have a Select Method.
VBA Coding Made Easy
Stop searching for VBA code online. Learn more about AutoMacro — A VBA Code Builder that allows beginners to code procedures from scratch with minimal coding knowledge and with many time-saving features for all users!
Learn More
Is Selecting Rows and Columns Necessary?
However, it’s (almost?) never necessary to actually select Rows or Columns. You don’t need to select a Row or Column in order to interact with them. Instead, you can apply Methods or Properties directly to the Rows or Columns. The next several sections will demonstrate different Methods and Properties that can be applied.
You can use any method listed above to refer to Rows or Columns.
Methods and Properties of Rows & Columns
Delete Entire Rows or Columns
To delete rows or columns, use the Delete Method:
Rows("1:4").Delete
or:
Columns("A:D").Delete
VBA Programming | Code Generator does work for you!
Insert Rows or Columns
Use the Insert Method to insert rows or columns:
Rows("1:4").Insert
or:
Columns("A:D").Insert
Copy & Paste Entire Rows or Columns
Paste Into Existing Row or Column
When copying and pasting entire rows or columns you need to decide if you want to paste over an existing row / column or if you want to insert a new row / column to paste your data.
These first examples will copy and paste over an existing row or column:
Range("1:1").Copy Range("5:5")
or
Range("C:C").Copy Range("E:E")
Insert & Paste
These next examples will paste into a newly inserted row or column.
This will copy row 1 and insert it into row 5, shifting the existing rows down:
Range("1:1").Copy
Range("5:5").Insert
This will copy column C and insert it into column E, shifting the existing columns to the right:
Range("C:C").Copy
Range("E:E").Insert
Hide / Unhide Rows and Columns
To hide rows or columns set their Hidden Properties to True. Use False to hide the rows or columns:
'Hide Rows
Rows("2:3").EntireRow.Hidden = True
'Unhide Rows
Rows("2:3").EntireRow.Hidden = False
or
'Hide Columns
Columns("B:C").EntireColumn.Hidden = True
'Unhide Columns
Columns("B:C").EntireColumn.Hidden = False
Group / UnGroup Rows and Columns
If you want to Group rows (or columns) use code like this:
'Group Rows
Rows("3:5").Group
'Group Columns
Columns("C:D").Group
To remove the grouping use this code:
'Ungroup Rows
Rows("3:5").Ungroup
'Ungroup Columns
Columns("C:D").Ungroup
This will expand all “grouped” outline levels:
ActiveSheet.Outline.ShowLevels RowLevels:=8, ColumnLevels:=8
and this will collapse all outline levels:
ActiveSheet.Outline.ShowLevels RowLevels:=1, ColumnLevels:=1
Set Row Height or Column Width
To set the column width use this line of code:
Columns("A:E").ColumnWidth = 30
To set the row height use this line of code:
Rows("1:1").RowHeight = 30
AutoMacro | Ultimate VBA Add-in | Click for Free Trial!
Autofit Row Height / Column Width
To Autofit a column:
Columns("A:B").Autofit
To Autofit a row:
Rows("1:2").Autofit
Rows and Columns on Other Worksheets or Workbooks
To interact with rows and columns on other worksheets, you must define the Sheets Object:
Sheets("Sheet2").Rows(3).Insert
Similarly, to interact with rows and columns in other workbooks, you must also define the Workbook Object:
Workbooks("book1.xlsm").Sheets("Sheet2").Rows(3).Insert
Get Active Row or Column
To get the active row or column, you can use the Row and Column Properties of the ActiveCell Object.
MsgBox ActiveCell.Row
or
MsgBox ActiveCell.Column
This also works with the Range Object:
MsgBox Range("B3").Column
VBA Select
It is very common to find the .Select methods in saved macro recorder code, next to a Range object.
.Select is used to select one or more elements of Excel (as can be done by using the mouse) allowing further manipulation of them.
Selecting cells with the mouse:
Selecting cells with VBA:
'Range([cell1],[cell2])
Range(Cells(1, 1), Cells(9, 5)).Select
Range("A1", "E9").Select
Range("A1:E9").Select
Each of the above lines select the range from «A1» to «E9».
VBA Select CurrentRegion
If a region is populated by data with no empty cells, an option for an automatic selection is the CurrentRegion property alongside the .Select method.
CurrentRegion.Select will select, starting from a Range, all the area populated with data.
Range("A1").CurrentRegion.Select
Make sure there are no gaps between values, as CurrentRegion will map the region through adjoining cells (horizontal, vertical and diagonal).
Range("A1").CurrentRegion.Select
With all the adjacent data
Not all adjacent data
«C4» is not selected because it is not immediately adjacent to any filled cells.
VBA ActiveCell
The ActiveCell property brings up the active cell of the worksheet.
In the case of a selection, it is the only cell that stays white.
A worksheet has only one active cell.
Range("B2:C4").Select
ActiveCell.Value = "Active"
Usually the ActiveCell property is assigned to the first cell (top left) of a Range, although it can be different when the selection is made manually by the user (without macros).
The AtiveCell property can be used with other commands, such as Resize.
VBA Selection
After selecting the desired cells, we can use Selection to refer to it and thus make changes:
Range("A1:D7").Select
Selection = 7
Selection also accepts methods and properties (which vary according to what was selected).
Selection.ClearContents 'Deletes only the contents of the selection
Selection.Interior.Color = RGB(255, 255, 0) 'Adds background color to the selection
As in this case a cell range has been selected, the Selection will behave similarly to a Range. Therefore, Selection should also accept the .Interior.Color property.
RGB (Red Green Blue) is a color system used in a number of applications and languages. The input values for each color, in the example case, ranges from 0 to 255.
Selection FillDown
If there is a need to replicate a formula to an entire selection, you can use the .FillDown method
Selection.FillDown
Before the FillDown
After the FillDown
.FillDown is a method applicable to Range. Since the Selection was done in a range of cells (equivalent to a Range), the method will be accepted.
.FillDown replicates the Range/Selection formula of the first line, regardless of which ActiveCell is selected.
.FillDown can be used at intervals greater than one column (E.g. Range(«B1:C2»).FillDown will replicate the formulas of B1 and C1 to B2 and C2 respectively).
VBA EntireRow and EntireColumn
You can select one or multiple rows or columns with VBA.
Range("B2").EntireRow.Select
Range("C3:D3").EntireColumn.Select
The selection will always refer to the last command executed with Select.
To insert a row use the Insert method.
Range("A7").EntireRow.Insert
'In this case, the content of the seventh row will be shifted downward
To delete a row use the Delete method.
Range("A7").EntireRow.Delete
'In this case, the content of the eighth row will be moved to the seventh
VBA Rows and Columns
Just like with the EntireRow and EntireColumn property, you can use Rows and Columns to select a row or column.
Columns(5).Select
Rows(3).Select
To hide rows:
Range("A1:C3").Rows.Hidden = True
In the above example, rows 1 to 3 of the worksheet were hidden.
VBA Row and Column
Row and Column are properties that are often used to obtain the numerical address of the first row or first column of a selection or a specific cell.
Range("A3:H30").Row 'Referring to the row; returns 3
Range("B3").Column 'Referring to the column; returns 2
The results of Row and Column are often used in loops or resizing.
Consolidating Your Learning
Suggested Exercise
SuperExcelVBA.com is learning website. Examples might be simplified to improve reading and basic understanding. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. All Rights Reserved.
Excel ® is a registered trademark of the Microsoft Corporation.
© 2023 SuperExcelVBA | ABOUT
Содержание
- Refer to Rows and Columns
- About the Contributor
- Support and feedback
- VBA – Select (and work with) Entire Rows & Columns
- Select Entire Rows or Columns
- Select Single Row
- Select Single Column
- Select Multiple Rows or Columns
- Select ActiveCell Row or Column
- Select Rows and Columns on Other Worksheets
- VBA Coding Made Easy
- Is Selecting Rows and Columns Necessary?
- Methods and Properties of Rows & Columns
- Delete Entire Rows or Columns
- Insert Rows or Columns
- Copy & Paste Entire Rows or Columns
- Paste Into Existing Row or Column
- Insert & Paste
- Hide / Unhide Rows and Columns
- Group / UnGroup Rows and Columns
- Set Row Height or Column Width
- Autofit Row Height / Column Width
- Rows and Columns on Other Worksheets or Workbooks
- Get Active Row or Column
- VBA Code Examples Add-in
- VBA Lesson 2-6: VBA for Excel for the Cells, Rows and Columns
- VBA Insert Row or Column
- Insert a Single Row or Column
- Insert New Row
- Insert New Column
- Insert Multiple Rows or Columns
- Insert Multiple Rows
- Insert Multiple Columns
- VBA Coding Made Easy
- Insert – Shift & CopyOrigin
- Other Insert Examples
- Insert Copied Rows or Columns
- Insert Rows Based on Cell Value
- Delete Rows or Columns
- VBA Code Examples Add-in
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.
Источник
VBA – Select (and work with) Entire Rows & Columns
In this Article
This tutorial will demonstrate how to select and work with entire rows or columns in VBA.
First we will cover how to select entire rows and columns, then we will demonstrate how to manipulate rows and columns.
Select Entire Rows or Columns
Select Single Row
You can select an entire row with the Rows Object like this:
Or you can use EntireRow along with the Range or Cells Objects:
You can also use the Range Object to refer specifically to a Row:
Select Single Column
Instead of the Rows Object, use the Columns Object to select columns. Here you can reference the column number 3:
or letter “C”, surrounded by quotations:
Instead of EntireRow, use EntireColumn along with the Range or Cells Objects to select entire columns:
You can also use the Range Object to refer specifically to a column:
Select Multiple Rows or Columns
Selecting multiple rows or columns works exactly the same when using EntireRow or EntireColumn:
However, when you use the Rows or Columns Objects, you must enter the row numbers or column letters in quotations:
Select ActiveCell Row or Column
To select the ActiveCell Row or Column, you can use one of these lines of code:
Select Rows and Columns on Other Worksheets
In order to select Rows or Columns on other worksheets, you must first select the worksheet.
The same goes for when selecting rows or columns in other workbooks.
Note: You must Activate the desired workbook. Unlike the Sheets Object, the Workbook Object does not have a Select Method.
VBA Coding Made Easy
Stop searching for VBA code online. Learn more about AutoMacro — A VBA Code Builder that allows beginners to code procedures from scratch with minimal coding knowledge and with many time-saving features for all users!
Is Selecting Rows and Columns Necessary?
However, it’s (almost?) never necessary to actually select Rows or Columns. You don’t need to select a Row or Column in order to interact with them. Instead, you can apply Methods or Properties directly to the Rows or Columns. The next several sections will demonstrate different Methods and Properties that can be applied.
You can use any method listed above to refer to Rows or Columns.
Methods and Properties of Rows & Columns
Delete Entire Rows or Columns
To delete rows or columns, use the Delete Method:
Insert Rows or Columns
Use the Insert Method to insert rows or columns:
Copy & Paste Entire Rows or Columns
Paste Into Existing Row or Column
When copying and pasting entire rows or columns you need to decide if you want to paste over an existing row / column or if you want to insert a new row / column to paste your data.
These first examples will copy and paste over an existing row or column:
Insert & Paste
These next examples will paste into a newly inserted row or column.
This will copy row 1 and insert it into row 5, shifting the existing rows down:
This will copy column C and insert it into column E, shifting the existing columns to the right:
Hide / Unhide Rows and Columns
To hide rows or columns set their Hidden Properties to True. Use False to hide the rows or columns:
Group / UnGroup Rows and Columns
If you want to Group rows (or columns) use code like this:
To remove the grouping use this code:
This will expand all “grouped” outline levels:
and this will collapse all outline levels:
Set Row Height or Column Width
To set the column width use this line of code:
To set the row height use this line of code:
Autofit Row Height / Column Width
To Autofit a row:
Rows and Columns on Other Worksheets or Workbooks
To interact with rows and columns on other worksheets, you must define the Sheets Object:
Similarly, to interact with rows and columns in other workbooks, you must also define the Workbook Object:
Get Active Row or Column
To get the active row or column, you can use the Row and Column Properties of the ActiveCell Object.
This also works with the Range Object:
VBA Code Examples Add-in
Easily access all of the code examples found on our site.
Simply navigate to the menu, click, and the code will be inserted directly into your module. .xlam add-in.
Источник
VBA Lesson 2-6: VBA for Excel for the Cells, Rows and Columns
Here is some code to move around and work with the components (rows, columns, cells and their values and formulas) of a worksheet.
Selection and ActiveCell
The object Selection comprises what is selected. It can be a single cell, many cells, a column, a row,many of these, a chart, an image or any other object.
For example:
Range(«A1:A30»).Select
Selection.ClearContents
will remove the content (values or formulas) of the cells A1 to A30..
The ActiveCell is the selected cell or the first cell of the range that you have selected. Try this in Excel:
— select column A and see that cell A1 is not highlighted as the other cells. It is the ActiveCell.
— select row 3 and see that A3 is the ActiveCell.
— select cells D3 to G13 starting with D3 and see that D3 is the ActiveCell
— now select the same range but start with G13. So select G13 to D3 and see that G13 is the ActiveCell
The ActiveCell is a very important concept that you will need to remember as you start developing more complex procedures.
Delete or ClearContents
BEWARE: If you write Range(«a2»).Delete the cell A2 is destroyed and cell A3 becomes cell A2 and all the formulas that refer to cell A2 are scrapped. If you use Range(«a2»).ClearContents only the value of cell A2 is removed. In VBA Delete is a big word use it with moderation and only when you really mean Delete.
Cells and ClearContents
To select all cells you will use
Cells.Select
And the to clear them all you will write:
Selection.ClearContents
or without selecting all the cells you can still clear them all with:
Cells.ClearContents
To select a cell you will write:
Range («A1»).Select
To select a set of contiguous cells you will write:
Range («A1:A5»).Select
To select a set of non contiguous cells you will write:
Range («A1,A5,B4»).Select
Columns, Rows, Select, EntireRow, EntireColumn
To select a column you will write:
Columns(«A»).Select
To select a set of contiguous columns you will write:
Columns («A:B»).Select
To select a set of non contiguous columns you will write:
Range(«A:A,C:C,E:E»).Select
To select a row you will write:
Rows(«1»).Select
To select a set of contiguous columns you will write:
Range(«1:1,3:3,6:6»).Select
To select a set of non contiguous columns you will write:
Rows(«1:13»).Select
You can also select the column or the row with this:
ActiveCell.EntireColumn.Select
ActiveCell.EntireRow.Select
Range(«A1»).EntireColumn.Select
Range(«A1»).EntireRow.Select
If more than one cell is selected the following code will select all rows and columns covered by the selection:
Selection.EntireColumn.Select
Selection.EntireRow.Select
When you know well your way around an Excel worksheet with VBA you can transform a set of raw data into a complex report like in: «vba-example-reporting.xls«
The Offset method is the one that you will use the most. It allows you to move right, left, up and down.
For example if you want to move 3 cells to the right, you will write:
Activecell.Offset(0,3).Select
If you want to move 3 cells to the left,
Activecell.Offset(0,-3).Select
Beware though if you are in column A this line will return an error message
If you want to move three cells down:
Activecell.Offset(3,0).Select
If you want to move three cells up:
Activecell.Offset(-3,0).Select
Here is a piece of code that you will use very frequently. If you want to select one cell and three more down:
Range(Activecell,Activecell.Offset(3,0)).Select
Range(«A1» ,Range(«A1»).Offset(3,0)).Select
When you want to enter a numerical value in a cell you will write:
Range(«A1»).Select
Selection.Value = 32
Note that you don’t need to select a cell to enter a value in it, from anywhere on the sheet you can write:
Range(«A1»).Value = 32
You can even change the value of cells on another sheet with:
Sheets(«SoAndSo»).Range(«A1»).Value = 32
BEWARE: When you send a value to a cell without selecting it the cursor doesn’t move and the Activecell remains the same it doesn’t become the cell in which you have just entered a value. So if you do Activecell.Offset(1,0).Select you will not move one cell down from the cell in which you have just entered a value but from the last cell that was selected.
You can also enter the same value in many cells with:
Range(«A1:B32»).Value = 32
If you want to enter a text in a cell you need to use the double quotes like:
Range(«A1»).Value = «Peter»
If you want to enter a text within double quotes showing in a cell you need to triple the double quotes like:
Range(«A1»).Value = «»» Peter»»»
When you want to enter a formula in a cell you will write:
Range(«A1»).Select
Selection.Formula = «=C8+C9»
Note the two equal signs (=) including the one within the double quotes like if you were entering it manually.
Again you don’t need to select a cell to enter a formula in it, from anywhere on the sheet you can write:
Range(«A1»).Formula = «=C8+C9»
If you write the following:
Range(«A1:A8»).Formula = «=C8+C9»
The formula in A1 will be =C8+C9, the formula in A2 will be =C9+C10 and so on. If you want to have the exact formula =C8+C9 in all the cells, you need to write:
Range(«A1:A8»).Formula = «=$C$8+$C$9»
If you have a date in cell A1 like January, 3 2007
Range(«A2)».Value = Month(Range(«A1»).Value the value entered in A2 will be 1
Range(«A2)».Value = Day(Range(«A1»).Value the value entered in A2 will be 3
Range(«A2)».Value = Year(Range(«A1»).Value the value entered in A2 will be 2007
Month and MonthName
As you have seen above:
Month(A1) will return «3» if there is «3/12/2007» in A1
But:
MonthName(Range(«A1»).Value) will return «January» if there is «1» in A1
MonthName(Range(«A1»).Value,True) will return «Feb» if there is «2» in A1
MonthName(Month(Range(«A1»).Value)) will return «March» if there is «3/12/2007» in A1
One of the most important property when working with sets of data and databases:
Selection.CurrentRegion.Select
will select all cells from the selection to the first empty row and the first empty column. See the lesson on databases to discover the importance of CurrentRegion
Column, Row, Columns, Rows, Count
For the following lines of code notice that you need to send the result into a variable. See lesson 2-9 on variables
Источник
VBA Insert Row or Column
In this Article
This tutorial will demonstrate how to use VBA to insert rows and columns in Excel.
To insert rows or columns we will use the Insert Method.
Insert a Single Row or Column
Insert New Row
To insert a single row, you can use the Rows Object:
Or you can use the Range Object along with EntireRow:
Insert New Column
Similar to inserting rows, we can use the Columns Object to insert a column:
Or the Range Object, along with EntireColumn:
Insert Multiple Rows or Columns
Insert Multiple Rows
When inserting multiple rows with the Rows Object, you must enter the rows in quotations:
Inserting multiple rows with the Range Object works the same as with a single row:
Insert Multiple Columns
When inserting multiple columns with the Columns Object, enter the column letters in quotations:
Inserting multiple columns with the Range Object works the same as with a single column:
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!
Insert – Shift & CopyOrigin
The Insert Method has two optional arguments:
- Shift – Which direction to shift the cells
- CopyOrigin – Which cell formatting to copy (above, below, left, or right)
The Shift argument is irrelevant when inserting entire rows or columns. It only allows you to indicate to shift down or shift to the right:
- xlShiftDown – Shift cells down
- xlShiftToRight – Shift cells to the right
As you can see, you can’t shift up or to the left.
The CopyOrigin argument has two potential inputs:
- xlFormatFromLeftorAbove – (0) Newly-inserted cells take formatting from cells above or to the left
- xlFormatFromRightorBelow (1) Newly-inserted cells take formatting from cells below or to the right.
Let’s look at some examples of the CopyOrigin argument. Here’s our initial data:
This example will insert a row, taking the formatting from the above row.
This example will insert a row, taking the formatting from the below row.
Other Insert Examples
Insert Copied Rows or Columns
If you’d like to insert a copied row, you would use code like this:
Here we copy Row 1 and Insert it at Row 5.
Insert Rows Based on Cell Value
Delete Rows or Columns
To delete rows or columns, simply use the Delete method.
VBA Code Examples Add-in
Easily access all of the code examples found on our site.
Simply navigate to the menu, click, and the code will be inserted directly into your module. .xlam add-in.
Источник
# Ways to refer to a single cell
The simplest way to refer to a single cell on the current Excel worksheet is simply to enclose the A1 form of its reference in square brackets:
Note that square brackets are just convenient syntactic sugar (opens new window) for the Evaluate
method of the Application
object, so technically, this is identical to the following code:
You could also call the Cells
method which takes a row and a column and returns a cell reference.
Remember that whenever you pass a row and a column to Excel from VBA, the row is always first, followed by the column, which is confusing because it is the opposite of the common A1
notation where the column appears first.
In both of these examples, we did not specify a worksheet, so Excel will use the active sheet (the sheet that is in front in the user interface). You can specify the active sheet explicitly:
Or you can provide the name of a particular sheet:
There are a wide variety of methods that can be used to get from one range to another. For example, the Rows
method can be used to get to the individual rows of any range, and the Cells
method can be used to get to individual cells of a row or column, so the following code refers to cell C1:
# Creating a Range
A Range (opens new window) cannot be created or populated the same way a string would:
It is considered best practice to qualify your references (opens new window), so from now on we will use the same approach here.
More about Creating Object Variables (e.g. Range) on MSDN (opens new window) . More about Set Statement on MSDN (opens new window).
There are different ways to create the same Range:
Note in the example that Cells(2, 1) is equivalent to Range(«A2»). This is because Cells returns a Range object.
Some sources: Chip Pearson-Cells Within Ranges (opens new window); MSDN-Range Object (opens new window); John Walkenback-Referring To Ranges In Your VBA Code (opens new window).
Also note that in any instance where a number is used in the declaration of the range, and the number itself is outside of quotation marks, such as Range(«A» & 2), you can swap that number for a variable that contains an integer/long. For example:
If you are using double loops, Cells is better:
# Offset Property
- Offset(Rows, Columns) — The operator used to statically reference another point from the current cell. Often used in loops. It should be understood that positive numbers in the rows section moves right, wheres as negatives move left. With the columns section positives move down and negatives move up.
i.e
This code selects B2, puts a new string there, then moves that string back to A1 afterwards clearing out B2.
# Saving a reference to a cell in a variable
To save a reference to a cell in a variable, you must use the Set
syntax, for example:
later…
Why is the Set
keyword required? Set
tells Visual Basic that the value on the right hand side of the =
is meant to be an object.
# How to Transpose Ranges (Horizontal to Vertical & vice versa)
Note: Copy/PasteSpecial also has a Paste Transpose option which updates the transposed cells’ formulas as well.
# Syntax
- Set — The operator used to set a reference to an object, such as a Range
- For Each — The operator used to loop through every item in a collection
Note that the variable names r
, cell
and others can be named however you like but should be named appropriately so the code is easier to understand for you and others.