I found a similar solution to this question in c# How to Select all the cells in a worksheet in Excel.Range object of c#?
What is the process to do this in VBA?
I select data normally by using «ctrl+shift over arrow, down arrow» to select an entire range of cells. When I run this in a macro it codes out A1:Q398247930, for example. I need it to just be
.SetRange Range("A1:whenever I run out of rows and columns")
I could easily do it myself without a macro, but I’m trying to make the entire process a macro, and this is just a piece of it.
Sub sort()
'sort Macro
Range("B2").Select
ActiveWorkbook.Worksheets("Master").sort.SortFields.Clear
ActiveWorkbook.Worksheets("Master").sort.SortFields.Add Key:=Range("B2"), _
SortOn:=xlSortOnValues, Order:=xlAscending, DataOption:=xlSortNormal
With ActiveWorkbook.Worksheets("Master").sort
.SetRange Range("A1:whenever I run out of rows and columns")
.Header = xlNo
.MatchCase = False
.Orientation = xlTopToBottom
.SortMethod = xlPinYin
.Apply
End With
End Sub
edit:
There are other parts where I might want to use the same code but the range is say «C3:End of rows & columns». Is there a way in VBA to get the location of the last cell in the document?
asked Jul 30, 2013 at 18:50
C. TewaltC. Tewalt
2,2612 gold badges29 silver badges47 bronze badges
I believe you want to find the current region of A1 and surrounding cells — not necessarily all cells on the sheet.
If so — simply use…
Range(«A1»).CurrentRegion
answered Jul 30, 2013 at 19:17
ExcelExpertExcelExpert
3522 silver badges4 bronze badges
1
You can simply use cells.select
to select all cells in the worksheet. You can get a valid address by saying Range(Cells.Address)
.
If you want to find the last Used Range
where you have made some formatting change or entered a value into you can call ActiveSheet.UsedRange
and select it from there. Hope that helps.
June7
19.5k8 gold badges24 silver badges33 bronze badges
answered Jul 30, 2013 at 19:11
chanceachancea
5,8083 gold badges28 silver badges39 bronze badges
2
you can use all cells as a object like this :
Dim x as Range
Set x = Worksheets("Sheet name").Cells
X is now a range object that contains the entire worksheet
answered Apr 15, 2015 at 11:47
you have a few options here:
- Using the UsedRange property
- find the last row and column used
- use a mimic of shift down and shift right
I personally use the Used Range and find last row and column method most of the time.
Here’s how you would do it using the UsedRange property:
Sheets("Sheet_Name").UsedRange.Select
This statement will select all used ranges in the worksheet, note that sometimes this doesn’t work very well when you delete columns and rows.
The alternative is to find the very last cell used in the worksheet
Dim rngTemp As Range
Set rngTemp = Cells.Find("*", SearchOrder:=xlByRows, SearchDirection:=xlPrevious)
If Not rngTemp Is Nothing Then
Range(Cells(1, 1), rngTemp).Select
End If
What this code is doing:
- Find the last cell containing any value
- select cell(1,1) all the way to the last cell
answered Jul 30, 2013 at 20:32
Derek ChengDerek Cheng
5353 silver badges8 bronze badges
3
Another way to select all cells within a range, as long as the data is contiguous, is to use Range("A1", Range("A1").End(xlDown).End(xlToRight)).Select
.
answered Mar 29, 2019 at 19:38
I would recommend recording a macro, like found in this post;
Excel VBA macro to filter records
But if you are looking to find the end of your data and not the end of the workbook necessary, if there are not empty cells between the beginning and end of your data, I often use something like this;
R = 1
Do While Not IsEmpty(Sheets("Sheet1").Cells(R, 1))
R = R + 1
Loop
Range("A5:A" & R).Select 'This will give you a specific selection
You are left with R = to the number of the row after your data ends. This could be used for the column as well, and then you could use something like Cells(C , R).Select, if you made C the column representation.
answered Jul 30, 2013 at 19:25
MakeCentsMakeCents
7321 gold badge5 silver badges15 bronze badges
2
Sub SelectAllCellsInSheet(SheetName As String)
lastCol = Sheets(SheetName).Range("a1").End(xlToRight).Column
Lastrow = Sheets(SheetName).Cells(1, 1).End(xlDown).Row
Sheets(SheetName).Range("A1", Sheets(SheetName).Cells(Lastrow, lastCol)).Select
End Sub
To use with ActiveSheet:
Call SelectAllCellsInSheet(ActiveSheet.Name)
answered Mar 14, 2017 at 20:57
Yehia AmerYehia Amer
5985 silver badges11 bronze badges
Here is what I used, I know it could use some perfecting, but I think it will help others…
''STYLING''
Dim sheet As Range
' Find Number of rows used
Dim Final As Variant
Final = Range("A1").End(xlDown).Row
' Find Last Column
Dim lCol As Long
lCol = Cells(1, Columns.Count).End(xlToLeft).Column
Set sheet = ActiveWorkbook.ActiveSheet.Range("A" & Final & "", Cells(1, lCol ))
With sheet
.Interior.ColorIndex = 1
End With
answered Mar 16, 2019 at 4:29
I have found that the Worksheet «.UsedRange» method is superior in many instances to solve this problem.
I struggled with a truncation issue that is a normal behaviour of the «.CurrentRegion» method. Using [ Worksheets(«Sheet1»).Range(«A1»).CurrentRegion ] does not yield the results I desired when the worksheet consists of one column with blanks in the rows (and the blanks are wanted). In this case, the «.CurrentRegion» will truncate at the first record. I implemented a work around but recently found an even better one; see code below that allows copying the whole set to another sheet or to identify the actual address (or just rows and columns):
Sub mytest_GetAllUsedCells_in_Worksheet()
Dim myRange
Set myRange = Worksheets("Sheet1").UsedRange
'Alternative code: set myRange = activesheet.UsedRange
'use msgbox or debug.print to show the address range and counts
MsgBox myRange.Address
MsgBox myRange.Columns.Count
MsgBox myRange.Rows.Count
'Copy the Range of data to another sheet
'Note: contains all the cells with that are non-empty
myRange.Copy (Worksheets("Sheet2").Range("A1"))
'Note: transfers all cells starting at "A1" location.
' You can transfer to another area of the 2nd sheet
' by using an alternate starting location like "C5".
End Sub
answered May 2, 2019 at 19:38
Maybe this might work:
Sh.Range(«A1», Sh.Range(«A» & Rows.Count).End(xlUp))
answered Oct 31, 2014 at 18:38
Refering to the very first question, I am looking into the same.
The result I get, recording a macro, is, starting by selecting cell A76:
Sub find_last_row()
Range("A76").Select
Range(Selection, Selection.End(xlDown)).Select
End Sub
answered Aug 7, 2015 at 12:40
title | keywords | f1_keywords | ms.prod | api_name | ms.assetid | ms.date | ms.localizationpriority |
---|---|---|---|---|---|---|---|
Range object (Excel) |
vbaxl10.chm143072 |
vbaxl10.chm143072 |
excel |
Excel.Range |
b8207778-0dcc-4570-1234-f130532cc8cd |
08/14/2019 |
high |
Range object (Excel)
Represents a cell, a row, a column, a selection of cells containing one or more contiguous blocks of cells, or a 3D range.
[!includeAdd-ins note]
Remarks
The default member of Range forwards calls without parameters to the Value property and calls with parameters to the Item member. Accordingly, someRange = someOtherRange
is equivalent to someRange.Value = someOtherRange.Value
, someRange(1)
to someRange.Item(1)
and someRange(1,1)
to someRange.Item(1,1)
.
The following properties and methods for returning a Range object are described in the Example section:
- Range and Cells properties of the Worksheet object
- Range and Cells properties of the Range object
- Rows and Columns properties of the Worksheet object
- Rows and Columns properties of the Range object
- Offset property of the Range object
- Union method of the Application object
Example
Use Range (arg), where arg names the range, to return a Range object that represents a single cell or a range of cells. The following example places the value of cell A1 in cell A5.
Worksheets("Sheet1").Range("A5").Value = _ Worksheets("Sheet1").Range("A1").Value
The following example fills the range A1:H8 with random numbers by setting the formula for each cell in the range. When it’s used without an object qualifier (an object to the left of the period), the Range property returns a range on the active sheet. If the active sheet isn’t a worksheet, the method fails.
Use the Activate method of the Worksheet object to activate a worksheet before you use the Range property without an explicit object qualifier.
Worksheets("Sheet1").Activate Range("A1:H8").Formula = "=Rand()" 'Range is on the active sheet
The following example clears the contents of the range named Criteria.
[!NOTE]
If you use a text argument for the range address, you must specify the address in A1-style notation (you cannot use R1C1-style notation).
Worksheets(1).Range("Criteria").ClearContents
Use Cells on a worksheet to obtain a range consisting all single cells on the worksheet. You can access single cells via Item(row, column), where row is the row index and column is the column index.
Item can be omitted since the call is forwarded to it by the default member of Range.
The following example sets the value of cell A1 to 24 and of cell B1 to 42 on the first sheet of the active workbook.
Worksheets(1).Cells(1, 1).Value = 24 Worksheets(1).Cells.Item(1, 2).Value = 42
The following example sets the formula for cell A2.
ActiveSheet.Cells(2, 1).Formula = "=Sum(B1:B5)"
Although you can also use Range("A1")
to return cell A1, there may be times when the Cells property is more convenient because you can use a variable for the row or column. The following example creates column and row headings on Sheet1. Be aware that after the worksheet has been activated, the Cells property can be used without an explicit sheet declaration (it returns a cell on the active sheet).
[!NOTE]
Although you could use Visual Basic string functions to alter A1-style references, it is easier (and better programming practice) to use theCells(1, 1)
notation.
Sub SetUpTable() Worksheets("Sheet1").Activate For TheYear = 1 To 5 Cells(1, TheYear + 1).Value = 1990 + TheYear Next TheYear For TheQuarter = 1 To 4 Cells(TheQuarter + 1, 1).Value = "Q" & TheQuarter Next TheQuarter End Sub
Use_expression_.Cells, where expression is an expression that returns a Range object, to obtain a range with the same address consisting of single cells.
On such a range, you access single cells via Item(row, column), where are relative to the upper-left corner of the first area of the range.
Item can be omitted since the call is forwarded to it by the default member of Range.
The following example sets the formula for cell C5 and D5 of the first sheet of the active workbook.
Worksheets(1).Range("C5:C10").Cells(1, 1).Formula = "=Rand()" Worksheets(1).Range("C5:C10").Cells.Item(1, 2).Formula = "=Rand()"
Use Range (cell1, cell2), where cell1 and cell2 are Range objects that specify the start and end cells, to return a Range object. The following example sets the border line style for cells A1:J10.
[!NOTE]
Be aware that the period in front of each occurrence of the Cells property is required if the result of the preceding With statement is to be applied to the Cells property. In this case, it indicates that the cells are on worksheet one (without the period, the Cells property would return cells on the active sheet).
With Worksheets(1) .Range(.Cells(1, 1), _ .Cells(10, 10)).Borders.LineStyle = xlThick End With
Use Rows on a worksheet to obtain a range consisting all rows on the worksheet. You can access single rows via Item(row), where row is the row index.
Item can be omitted since the call is forwarded to it by the default member of Range.
[!NOTE]
It’s not legal to provide the second parameter of Item for ranges consisting of rows. You first have to convert it to single cells via Cells.
The following example deletes row 5 and 10 of the first sheet of the active workbook.
Worksheets(1).Rows(10).Delete Worksheets(1).Rows.Item(5).Delete
Use Columns on a worksheet to obtain a range consisting all columns on the worksheet. You can access single columns via Item(row) [sic], where row is the column index given as a number or as an A1-style column address.
Item can be omitted since the call is forwarded to it by the default member of Range.
[!NOTE]
It’s not legal to provide the second parameter of Item for ranges consisting of columns. You first have to convert it to single cells via Cells.
The following example deletes column «B», «C», «E», and «J» of the first sheet of the active workbook.
Worksheets(1).Columns(10).Delete Worksheets(1).Columns.Item(5).Delete Worksheets(1).Columns("C").Delete Worksheets(1).Columns.Item("B").Delete
Use_expression_.Rows, where expression is an expression that returns a Range object, to obtain a range consisting of the rows in the first area of the range.
You can access single rows via Item(row), where row is the relative row index from the top of the first area of the range.
Item can be omitted since the call is forwarded to it by the default member of Range.
[!NOTE]
It’s not legal to provide the second parameter of Item for ranges consisting of rows. You first have to convert it to single cells via Cells.
The following example deletes the ranges C8:D8 and C6:D6 of the first sheet of the active workbook.
Worksheets(1).Range("C5:D10").Rows(4).Delete Worksheets(1).Range("C5:D10").Rows.Item(2).Delete
Use_expression_.Columns, where expression is an expression that returns a Range object, to obtain a range consisting of the columns in the first area of the range.
You can access single columns via Item(row) [sic], where row is the relative column index from the left of the first area of the range given as a number or as an A1-style column address.
Item can be omitted since the call is forwarded to it by the default member of Range.
[!NOTE]
It’s not legal to provide the second parameter of Item for ranges consisting of columns. You first have to convert it to single cells via Cells.
The following example deletes the ranges L2:L10, G2:G10, F2:F10 and D2:D10 of the first sheet of the active workbook.
Worksheets(1).Range("C5:Z10").Columns(10).Delete Worksheets(1).Range("C5:Z10").Columns.Item(5).Delete Worksheets(1).Range("C5:Z10").Columns("D").Delete Worksheets(1).Range("C5:Z10").Columns.Item("B").Delete
Use Offset (row, column), where row and column are the row and column offsets, to return a range at a specified offset to another range. The following example selects the cell three rows down from and one column to the right of the cell in the upper-left corner of the current selection. You cannot select a cell that is not on the active sheet, so you must first activate the worksheet.
Worksheets("Sheet1").Activate 'Can't select unless the sheet is active Selection.Offset(3, 1).Range("A1").Select
Use Union (range1, range2, …) to return multiple-area ranges—that is, ranges composed of two or more contiguous blocks of cells. The following example creates an object defined as the union of ranges A1:B2 and C3:D4, and then selects the defined range.
Dim r1 As Range, r2 As Range, myMultiAreaRange As Range Worksheets("sheet1").Activate Set r1 = Range("A1:B2") Set r2 = Range("C3:D4") Set myMultiAreaRange = Union(r1, r2) myMultiAreaRange.Select
If you work with selections that contain more than one area, the Areas property is useful. It divides a multiple-area selection into individual Range objects and then returns the objects as a collection. Use the Count property on the returned collection to verify a selection that contains more than one area, as shown in the following example.
Sub NoMultiAreaSelection() NumberOfSelectedAreas = Selection.Areas.Count If NumberOfSelectedAreas > 1 Then MsgBox "You cannot carry out this command " & _ "on multi-area selections" End If End Sub
This example uses the AdvancedFilter method of the Range object to create a list of the unique values, and the number of times those unique values occur, in the range of column A.
Sub Create_Unique_List_Count() 'Excel workbook, the source and target worksheets, and the source and target ranges. Dim wbBook As Workbook Dim wsSource As Worksheet Dim wsTarget As Worksheet Dim rnSource As Range Dim rnTarget As Range Dim rnUnique As Range 'Variant to hold the unique data Dim vaUnique As Variant 'Number of unique values in the data Dim lnCount As Long 'Initialize the Excel objects Set wbBook = ThisWorkbook With wbBook Set wsSource = .Worksheets("Sheet1") Set wsTarget = .Worksheets("Sheet2") End With 'On the source worksheet, set the range to the data stored in column A With wsSource Set rnSource = .Range(.Range("A1"), .Range("A100").End(xlDown)) End With 'On the target worksheet, set the range as column A. Set rnTarget = wsTarget.Range("A1") 'Use AdvancedFilter to copy the data from the source to the target, 'while filtering for duplicate values. rnSource.AdvancedFilter Action:=xlFilterCopy, _ CopyToRange:=rnTarget, _ Unique:=True 'On the target worksheet, set the unique range on Column A, excluding the first cell '(which will contain the "List" header for the column). With wsTarget Set rnUnique = .Range(.Range("A2"), .Range("A100").End(xlUp)) End With 'Assign all the values of the Unique range into the Unique variant. vaUnique = rnUnique.Value 'Count the number of occurrences of every unique value in the source data, 'and list it next to its relevant value. For lnCount = 1 To UBound(vaUnique) rnUnique(lnCount, 1).Offset(0, 1).Value = _ Application.Evaluate("COUNTIF(" & _ rnSource.Address(External:=True) & _ ",""" & rnUnique(lnCount, 1).Text & """)") Next lnCount 'Label the column of occurrences with "Occurrences" With rnTarget.Offset(0, 1) .Value = "Occurrences" .Font.Bold = True End With End Sub
Methods
- Activate
- AddComment
- AddCommentThreaded
- AdvancedFilter
- AllocateChanges
- ApplyNames
- ApplyOutlineStyles
- AutoComplete
- AutoFill
- AutoFilter
- AutoFit
- AutoOutline
- BorderAround
- Calculate
- CalculateRowMajorOrder
- CheckSpelling
- Clear
- ClearComments
- ClearContents
- ClearFormats
- ClearHyperlinks
- ClearNotes
- ClearOutline
- ColumnDifferences
- Consolidate
- ConvertToLinkedDataType
- Copy
- CopyFromRecordset
- CopyPicture
- CreateNames
- Cut
- DataTypeToText
- DataSeries
- Delete
- DialogBox
- Dirty
- DiscardChanges
- EditionOptions
- ExportAsFixedFormat
- FillDown
- FillLeft
- FillRight
- FillUp
- Find
- FindNext
- FindPrevious
- FlashFill
- FunctionWizard
- Group
- Insert
- InsertIndent
- Justify
- ListNames
- Merge
- NavigateArrow
- NoteText
- Parse
- PasteSpecial
- PrintOut
- PrintPreview
- RemoveDuplicates
- RemoveSubtotal
- Replace
- RowDifferences
- Run
- Select
- SetCellDataTypeFromCell
- SetPhonetic
- Show
- ShowCard
- ShowDependents
- ShowErrors
- ShowPrecedents
- Sort
- SortSpecial
- Speak
- SpecialCells
- SubscribeTo
- Subtotal
- Table
- TextToColumns
- Ungroup
- UnMerge
Properties
- AddIndent
- Address
- AddressLocal
- AllowEdit
- Application
- Areas
- Borders
- Cells
- Characters
- Column
- Columns
- ColumnWidth
- Comment
- CommentThreaded
- Count
- CountLarge
- Creator
- CurrentArray
- CurrentRegion
- Dependents
- DirectDependents
- DirectPrecedents
- DisplayFormat
- End
- EntireColumn
- EntireRow
- Errors
- Font
- FormatConditions
- Formula
- FormulaArray
- FormulaHidden
- FormulaLocal
- FormulaR1C1
- FormulaR1C1Local
- HasArray
- HasFormula
- HasRichDataType
- Height
- Hidden
- HorizontalAlignment
- Hyperlinks
- ID
- IndentLevel
- Interior
- Item
- Left
- LinkedDataTypeState
- ListHeaderRows
- ListObject
- LocationInTable
- Locked
- MDX
- MergeArea
- MergeCells
- Name
- Next
- NumberFormat
- NumberFormatLocal
- Offset
- Orientation
- OutlineLevel
- PageBreak
- Parent
- Phonetic
- Phonetics
- PivotCell
- PivotField
- PivotItem
- PivotTable
- Precedents
- PrefixCharacter
- Previous
- QueryTable
- Range
- ReadingOrder
- Resize
- Row
- RowHeight
- Rows
- ServerActions
- ShowDetail
- ShrinkToFit
- SoundNote
- SparklineGroups
- Style
- Summary
- Text
- Top
- UseStandardHeight
- UseStandardWidth
- Validation
- Value
- Value2
- VerticalAlignment
- Width
- Worksheet
- WrapText
- XPath
See also
- Excel Object Model Reference
[!includeSupport and feedback]
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
This example teaches you how to select entire rows and columns in Excel VBA. Are you ready?
Place a command button on your worksheet and add the following code lines:
1. The following code line selects the entire sheet.
Cells.Select
Note: because we placed our command button on the first worksheet, this code line selects the entire first sheet. To select cells on another worksheet, you have to activate this sheet first. For example, the following code lines select the entire second worksheet.
Worksheets(2).Activate
Worksheets(2).Cells.Select
2. The following code line selects the second column.
Columns(2).Select
3. The following code line selects the seventh row.
Rows(7).Select
4. To select multiple rows, add a code line like this:
Rows(«5:7»).Select
5. To select multiple columns, add a code line like this:
Columns(«B:E»).Select
6. Be careful not to mix up the Rows and Columns properties with the Row and Column properties. The Rows and Columns properties return a Range object. The Row and Column properties return a single value.
Code line:
MsgBox Cells(5, 2).Row
Result:
7. Select cell D6. The following code line selects the entire row of the active cell.
ActiveCell.EntireRow.Select
Note: border for illustration only.
8. Select cell D6. The following code line enters the value 2 into the first cell of the column that contains the active cell.
ActiveCell.EntireColumn.Cells(1).Value = 2
Note: border for illustration only.
9. Select cell D6. The following code line enters the value 3 into the first cell of the row below the row that contains the active cell.
ActiveCell.EntireRow.Offset(1, 0).Cells(1).Value = 3
Note: border for illustration only.
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