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?
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
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
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
.
you have a few options here:
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:
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)