Find last row in range

前端 未结 11 2039
傲寒
傲寒 2020-12-02 00:41

I\'m having a little trouble with finding the last row.

What I am trying to do is find the last row in column "A", then use that to find the last row within

11条回答
  •  半阙折子戏
    2020-12-02 01:21

    There are mulitple results and methods when searching for the LastRow (in Column B).

    When using Cells(.Rows.Count, "B").End(xlUp).Row you will get the last row with data in Column B (it ignores rows with spaces, and goes all the way down).

    When using:

     With wbshtSelect.Range("B10").CurrentRegion
         LR_wbSelectNew = .Rows(.Rows.Count).Row
     End With
    

    You are searching for the last row with data in Column B of the CurrentRegion, that starts from cell B10, untill the first line without data (it stops on the first row with empty row).

    Full Code:

    Sub GetLastRow()
    
    Dim wbshtSelect         As Worksheet
    Dim LR_wbSelectNew      As Long
    
    ' modify "Sheet2" to your sheet's name
    Set wbshtSelect = Sheets("Sheet2")
    
    ' find last row with data in Column B
    With wbshtSelect
        LR_wbSelectNew = .Cells(.Rows.Count, "B").End(xlUp).Row
    End With
    ' for debug only
    Debug.Print LR_wbSelectNew ' >>result 31
    
    ' find last row with data in Column B at current regioun starting at cell B10
    With wbshtSelect.Range("B10").CurrentRegion
        LR_wbSelectNew = .Rows(.Rows.Count).Row
    End With
    ' for debug only
    Debug.Print LR_wbSelectNew ' >> result 18
    
    End Sub
    

    Edit1: code searches for last row for cells with values (it ignores blank cells with formulas inside).

    Sub GetLastRow()
    
    Dim wbshtSelect         As Worksheet
    Dim LR_wbSelectNew      As Long
    
    ' modify "Sheet2" to your sheet's name
    Set wbshtSelect = Sheets("Sheet2")
    
    ' find last row with data in Column B at current regioun starting at cell B10
    With wbshtSelect.Range("B10").CurrentRegion
        LR_wbSelectNew = .Rows(.Rows.Count).Row
    End With
    
    Dim Rng         As Range    
    Set Rng = wbshtSelect.Range("B10:B" & LR_wbSelectNew)
    
    ' find last row inside the range, ignore values inside formulas
    LR_wbSelectNew = Rng.Find(What:="*", _
                        After:=Range("B10"), _
                        LookAt:=xlPart, _
                        LookIn:=xlValues, _
                        SearchOrder:=xlByRows, _
                        SearchDirection:=xlPrevious, _
                        MatchCase:=False).Row
    
    ' for debug
    Debug.Print LR_wbSelectNew  ' << result 18 (with formulas in the range)
    
    End Sub
    

提交回复
热议问题