I\'m new here and I\'m looking to use Excel VBA to return the last used cell in a worksheet.
I\'vv looked at Error in finding last used cell in Excel with VBA) but that d
Use Find
both by row and column to identify this cell.
Sub GetLastCellRange()
Dim rng1 As Range
Dim rng2 As Range
Dim rng3 As Range
Set rng1 = Cells.Find("*", [a1], xlFormulas, , xlByRows, xlPrevious)
Set rng2 = Cells.Find("*", [a1], xlFormulas, , xlByColumns, xlPrevious)
If Not rng1 Is Nothing Then
Set rng3 = Range([a1], Cells(rng1.Row, rng2.Column))
MsgBox "Range is " & rng3.Address(0, 0)
'if you need to actual select the range (which is rare in VBA)
Application.Goto rng3
Else
MsgBox "sheet is blank", vbCritical
End If
End Sub
Although the answers are very valid, I'd be careful using SpecialCells, CurrentRegion and all those.
Although they work most of the time, they are not 100% reliable in my experience.
For example, CurrentRegion will not pick up all data if the data happens to have an empty column or row etc.
The best Approach, in my opinion is to always use headers with your data. You can then enumerate all headers and find the last used row in that column. You can then determine the greatest row used and now define your data range.
Btw, if you select the last cell in a specified column then use the Range.End(xlUp) you can quickly determine the last used row for that column without Looping.
Did you try this?
Dim r As Range
Set r = Sheet1.UsedRange.SpecialCells(xlCellTypeLastCell)
Debug.Print r.Address
Output for your example:
$D$4
The UsedRange is known to not always match the actually used data range. Some workaround would be to use CurrentRegion
:
Dim r As Range
With Sheet1.Range("A1").CurrentRegion
Set r = Sheet1.Cells(.Rows.count, .Columns.count)
End With
Debug.Print r.Address
also if the data does not start at A1
, maybe this:
With Sheet1.Cells.Find("*").CurrentRegion