[英]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列的行,因為公式引用不同工作表上的單個單元格並動態添加。
我認為比@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
您希望在列中找到非空的最后一個單元格,而不是空字符串(“”)。
只需跟隨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
未指定哪個工作表。 這意味着它將使用活動表。 當然, ActiveSheet.Range()
也在活動表上。 但它是不好的做法,混合Range
或Rows
與.Range
或.Rows
。 它表示如果您更改了ActiveSheet
但沒有更改未指定的引用,可能會讓您感到輕率。
這應該可以幫助您確定包含公式的最后一行(在Sheet1
A
列Sheet1
):
lastRow = Split(Split(Sheet1.Range("A:A").SpecialCells(xlCellTypeFormulas).Address, ",")(UBound(Split(Sheet1.Range("A:A").SpecialCells(xlCellTypeFormulas).Address, ","))), "$")(2)
SpecialCells
用於確定包含公式的所有單元格的范圍。 然后使用Split
解析此范圍。 使用Ubound
,正在檢索這些單元格中的最后一個。 結果再次拆分以提取行號。
Function returnLastRow()
With ActiveSheet.UsedRange
returnLastRow = .Find("*", , xlValues, , xlByRows, xlPrevious).Row
End With
End Function
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.