This question is now answered elegantly, thanks to Chris Neilsen, see the answer below. It is the one I will use from now on. The solution reliably finds the last cell in
Great question.
As you note, Find
failes with AutoFilter. As an alternative to looping through the filters, or the range loop used by another answer you could
AutoFilter
Find
routine which caters to hidden cellsSo something lke this:
Sub GetRange()
'by Brettdj, http://stackoverflow.com/questions/8283797/return-a-range-from-a1-to-the-true-last-used-cell
Dim rng1 As Range
Dim rng2 As Range
Dim rng3 As Range
Dim ws As Worksheet
With Application
.EnableEvents = False
.ScreenUpdating = False
End With
ActiveSheet.Copy
Set ws = ActiveSheet
With ws
.AutoFilterMode = False
Set rng1 = ws.Cells.Find("*", ws.[a1], xlFormulas, , xlByRows, xlPrevious)
Set rng2 = ws.Cells.Find("*", ws.[a1], xlFormulas, xlPart, xlByColumns, xlPrevious)
If Not rng1 Is Nothing Then
Set rng3 = Range([a1], Cells(rng1.Row, rng2.Column))
MsgBox "Range is " & rng3.Address(0, 0)
Debug.Print "Brettdj's GetRange gives: Range is " & rng3.Address(0, 0) 'added for this test by ND
'if you need to actual select the range (which is rare in VBA)
Application.GoTo rng3
Else
MsgBox "sheet is blank", vbCritical
End If
.Parent.Close False
End With
With Application
.EnableEvents = True
.ScreenUpdating = True
End With
End Sub