How to find the true Last Cell in any Worksheet

前端 未结 5 1817
遇见更好的自我
遇见更好的自我 2021-01-13 01:12

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

5条回答
  •  生来不讨喜
    2021-01-13 01:47

    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

    • Copy the sheet and remove the AutoFilter
    • use xlformulas in the Find routine which caters to hidden cells

    So 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
    

提交回复
热议问题