When I want to find the last used cell value, I use:
Dim LastRow As Long
LastRow = Range("E4:E48").End(xlDown).Row
Debug.Print LastRow
I’m getting the wrong output when I put a single element into a cell. But when I put more than one value into the cell, the output is correct.
What’s the reason behind this?
NOTE: I intend to make this a “one stop post” where you can use the
Correctway to find the last row. This will also cover the best practices to follow when finding the last row. And hence I will keep on updating it whenever I come across a new scenario/information.Unreliable ways of finding the last row
Some of the most common ways of finding last row which are highly unreliable and hence should never be used.
UsedRangeshould NEVER be used to find the last cell which has data. It is highly unreliable. Try this experiment.Type something in cell
A5. Now when you calculate the last row with any of the methods given below, it will give you 5. Now color the cellA10red. If you now use the any of the below code, you will still get 5. If you useUsedrange.Rows.Countwhat do you get? It won’t be 5.Here is a scenario to show how
UsedRangeworks.xlDownis equally unreliable.Consider this code
What would happen if there was only one cell (
A1) which had data? You will end up reaching the last row in the worksheet! It’s like selecting cellA1and then pressing End key and then pressing Down Arrow key. This will also give you unreliable results if there are blank cells in a range.CountAis also unreliable because it will give you incorrect result if there are blank cells in between.And hence one should avoid the use of
UsedRange,xlDownandCountAto find the last cell.Find Last Row in a Column
To find the last Row in Col E use this
If you notice that we have a
.beforeRows.Count. We often chose to ignore that. See THIS question on the possible error that you may get. I always advise using.beforeRows.CountandColumns.Count. That question is a classic scenario where the code will fail because theRows.Countreturns65536for Excel 2003 and earlier and1048576for Excel 2007 and later. SimilarlyColumns.Countreturns256and16384, respectively.The above fact that Excel 2007+ has
1048576rows also emphasizes on the fact that we should always declare the variable which will hold the row value asLonginstead ofIntegerelse you will get anOverflowerror.Note that this approach will skip any hidden rows. Looking back at my screenshot above for column A, if row 8 were hidden, this approach would return
5instead of8.Find Last Row in a Sheet
To find the
Effectivelast row in the sheet, use this. Notice the use ofApplication.WorksheetFunction.CountA(.Cells). This is required because if there are no cells with data in the worksheet then.Findwill give youRun Time Error 91: Object Variable or With block variable not setFind Last Row in a Table (ListObject)
The same principles apply, for example to get the last row in the third column of a table: