在包含公式的一系列单元格中查找最后一个非空行

Find the last not empty row in a range of cells holding a formula

如何找到包含公式的单元格区域的最后一行,其中公式的结果是实际值而不是空值?

用简化的方式说,单元格范围 ("E1:E10") 包含引用单元格 A1 到 A10 的公式,如下所示 =IF("A1"="","","A1")。但只有单元格 A1 到 A6 填充了值,因此单元格 E7 到 E10 的公式结果将为空。

尝试使用:

lastRow = ActiveSheet.Range("E" & Rows.Count).End(xlUp).Row

导致 lastRow 的值为 10。在这个例子中,我想要的是 lastRow 的值是 6

实际代码比这复杂得多,所以我不能只检查 A 列最后填充的行,因为公式引用不同工作表上的单个单元格并且是动态添加的。

这应该可以帮助您确定包含公式的最后一行(在工作表 1 Sheet1A 列中):

lastRow  = Split(Split(Sheet1.Range("A:A").SpecialCells(xlCellTypeFormulas).Address, ",")(UBound(Split(Sheet1.Range("A:A").SpecialCells(xlCellTypeFormulas).Address, ","))), "$")(2)

SpecialCells用于确定包含公式的所有单元格的范围。然后使用 Split 解析此范围。 Ubound 正在检索这些单元格中的最后一个。结果正在再次拆分以提取行号。

您想查找列中最后一个非空且不是空字符串 ("") 的单元格。

只需在 LastRow 之后循环检查非空白单元格。

lastrow = ActiveSheet.Range("E" & ActiveSheet.Rows.Count).End(xlUp).Row
Do
    If ActiveSheet.Cells(lastrow, 5).Value <> "" Then
        Exit Do
    End If
    lastrow = lastrow - 1
Loop While lastrow > 0

If lastrow > 0 Then
    Debug.Print "Last row with data: " & lastrow
Else
    Debug.Print "No data in the column"
End If

请注意,您的 Rows.count 没有指定哪个 sheet。这意味着它将使用活动 sheet。当然 ActiveSheet.Range() 也是活跃的 sheet。但是将 RangeRows.Range.Rows 混合使用是不好的做法。如果您更改了 ActiveSheet 但没有更改未指定的引用,它表示一种轻率的用法可能会伤害您。

我认为比 @D_Bester 提供的更优雅的方法是使用 find() 选项而不循环遍历单元格范围:

Sub test()
    Dim cl As Range, i&
    Set cl = Range("E1:E" & Cells(Rows.Count, "E").End(xlUp).Row)
    i = cl.Find("*", , xlValues, , xlByRows, xlPrevious).Row
    Debug.Print "Last row with data: " & i
End Sub

测试

此外,上面提供的代码的更短版本是:

Sub test2()
    Debug.Print [E:E].Find("*", , xlValues, , xlByRows, xlPrevious).Row
End Sub
Function returnLastRow()
    With ActiveSheet.UsedRange
    returnLastRow = .Find("*", , xlValues, , xlByRows, xlPrevious).Row
    End With
End Function