gpt4 book ai didi

excel - 查找范围内的最后一行

转载 作者:行者123 更新时间:2023-12-02 07:16:44 25 4
gpt4 key购买 nike

我在找到最后一行时遇到了一些麻烦。

我想做的是找到“A”列中的最后一行,然后用它来查找范围内的最后一行。

数据示例:

Example of data

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

2) LR_wbSelectNew = wbshtSelect.cells(LR_wbSelect, "A").End(xlUp).Row

我使用“A”列中的最后一行,因为第 29 行往下的数据将始终具有相同的长度,第 29 行的“B”列中使用的行可以是不同的行数。

因此,我尝试在“A”列中使用 LR_wbSelect 来获取起始最后一行,然后在 LR_wbSelectNew 中使用它作为查找的起点。

当我将列设置为“A”时,LR_wbSelectNew 会为我提供“17”行,但当我将 LR_wbSelectNew 中的列更改为“B”时,此功能有效“它没有给出正确的最后一行“18”。

我可以将列更改为“C、D、E、F”,并且代码可以正常工作,但我可以使用的唯一列是“B”,因为它始终包含数据,而其余的则在其中行可以有一个空白单元格。

在工作表上进行一些测试后,通过从 LR_wbSelect 列“B”的最后一个点按 CRTL 和向上键会忽略行中的数据并转到它找到的行数据。我不明白 Excel 认为这些单元格中没有数据的原因?

最佳答案

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

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

使用时:

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

您正在搜索 CurrentRegion 的 B 列中包含数据的最后一行,该行从单元格 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

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

关于excel - 查找范围内的最后一行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40650508/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com