How to find the true Last Cell in any Worksheet

前端 未结 5 1922
遇见更好的自我
遇见更好的自我 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 02:01

    UsedRange may be erroneous, (it may be too large), but we can start with its outer limits and work inwards:

    Sub TrueLastCell()
        Dim lr As Long, lc As Long, i As Long
        Dim wf As WorksheetFunction
        Set wf = Application.WorksheetFunction
    
        ActiveSheet.UsedRange
        With ActiveSheet.UsedRange
            lr = .Rows.Count + .Row - 1
            lc = .Columns.Count + .Column - 1
        End With
    
        For i = lr To 1 Step -1
            If wf.CountA(Rows(i)) <> 0 Then
                Exit For
            End If
        Next i
    
        For i = lc To 1 Step -1
            If wf.CountA(Cells(lr, i)) <> 0 Then
                MsgBox "The TRUE last cell is " & Cells(lr, i).Address(0, 0)
                Exit Sub
            End If
        Next i
    End Sub
    

提交回复
热议问题