Excel VBA查找范围中的最后一行

ata*_*ame 5 excel vba excel-vba excel-2010

我找到最后一排有点麻烦.

我想要做的是找到"A"列中的最后一行,然后使用它来查找范围内的最后一行.

数据示例:

数据示例

 1) LR_wbSelect = wbshtSelect.cells(Rows.count, "A").End(xlUp).Row - 22

 2) LR_wbSelectNew = wbshtSelect.cells(LR_wbSelect, "A").End(xlUp).Row
Run Code Online (Sandbox Code Playgroud)

我使用列"A"中的最后一行,因为来自第29行的数据将始终具有相同的长度,来自第29行的列"B"中使用的行可以是不同数量的行.

所以我想LR_wbSelect在列"A"中使用以获得我的最后一行,然后LR_wbSelectNew使用它作为查找的起点.

当我将列设置为"A"时,这LR_wbSelectNew会产生"17"行,但是当我将列更改LR_wbSelectNew为"B"时,它不会给出正确的最后一行"18".

我可以将列更改为"C,D,E,F"并且代码工作正常,但我可以使用的唯一列是"B",因为它将始终包含数据,其中该行的其余部分可能具有一个空白单元格.

在工作表上进行一些测试后,通过从LR_wbSelect列"B" 的拉伸点按CRTL&Up 忽略行中的数据并转到找到数据的行.我看不出为什么excel不认为这些单元格中有数据?

希望我已经解释过,所以你可以关注,如果不是,请问.

如果需要,我可以根据需要上传完整的代码,请告诉我.

任何帮助,将不胜感激.

Sha*_*ado 8

搜索LastRow时有多种结果和方法(在B列中).

使用时,Cells(.Rows.Count, "B").End(xlUp).Row您将获得B列中数据的最后一行(它忽略带空格的行,并一直向下).

使用时:

 With wbshtSelect.Range("B10").CurrentRegion
     LR_wbSelectNew = .Rows(.Rows.Count).Row
 End With
Run Code Online (Sandbox Code Playgroud)

您正在搜索最后一行,其中B列中的数据CurrentRegion从单元格B10开始,直到没有数据的第一行(它在第一行有空行的情况下停止).

完整代码:

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
Run Code Online (Sandbox Code Playgroud)

Edit1:代码搜索具有值的单元格的最后一行(它忽略带有公式的空白单元格).

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
Run Code Online (Sandbox Code Playgroud)