Question posted 2015 · +7 upvotes
How can I find the last row in a range of cells that hold a formula, where the result of the formula is an actual value and not empty?
Say in a simplified way that the range of cells ("E1:E10") hold a formula referring to cells A1 through A10 as followed =IF("A1"="","","A1"). But only the cells A1 through A6 have a value filled in, so the result of the formula for cells E7 through E10 will be empty.
Trying to do it with:
lastRow = ActiveSheet.Range("E" & Rows.Count).End(xlUp).Row
results in lastRow having the value of 10. What I want is for the value of lastRow to be 6 in this example.
The actual code is way more complex than this so I can’t just check for the last filled in Row of Column A, as the formulas refer to single cells on different sheets and are added dynamically.
Accepted answer +6 upvotes
I think that more elegant way than was provided by @D_Bester is to use find() option without looping through the range of cells:
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
test
Also, more shorter version of the code which was provided above is:
Sub test2()
Debug.Print [E:E].Find("*", , xlValues, , xlByRows, xlPrevious).Row
End Sub
2 code variants in this answer
- Variant 1 — 6 lines, starts with
Sub test() - Variant 2 — 3 lines, starts with
Sub test2()
Excel VBA objects referenced (4)
ActiveSheet.Range— Refer to Cells by Using a Range ObjectActiveSheet.Range— Delete Duplicate Entries in a RangeRows.Count— Count function (Microsoft Access SQL)Rows.Count— Count the number of records in a DAO Recordset
Top excel-vba Q&A (6)
- How to clear the entire array? +58 (2010)
- How to change Format of a Cell to Text using VBA +55 (2011)
- Download attachment from Outlook and Open in Excel +43 (2012)
- Can a VBA function in Excel return a range? +36 (2009)
- 2 Dimensional array from range +34 (2013)
- Hiding an Excel worksheet with VBA +33 (2009)
excel-vba solutions on this site
.