column A has data like this (ie frequent blank cells):
HEADING <-- this is A1
kfdsl
fdjgnm
fdkj
gdfkj
4353
fdjk <-- this is A9
I would like to be able to get the cell reference of the last cell that has data. So in the above example I want to return: A9
I have tried this but it stops at the first blank cell (ie returning A4
)
numofrows = destsheet.Range("A2").End(xlDown).Row - 1
I compared all possibilities with a long test sheet:
0,140625 sec for
0 sec for
and
0,0078125 sec for
I think the favourites are obvious...
I like this way:
ActiveSheet.UsedRange.Rows.Count
The same can be done with columns count. For me, always work. But, if you have data in another columns, the code above will consider them too, because the code is looking for all cell range in the sheet.
Safest option is
Don't use
UsedRange
orSpecialCells(xlLastCell)
orEnd(xlUp)
. All these methods may give wrong results if you previously deleted some rows. Excel still counts these invisible cells.These methods will work again if you delete your cells, save the workbook, close and re-open it.
Found this approach on another site. It works with the new larger sizes of Excel and doesn't require you to hardcode the max number of rows and columns.
Thanks to mudraker in Melborne, Australia
This will work, independent of Excel version (2003, 2007, 2010). The first has 65536 rows in a sheet, while the latter two have a million rows or so.
Sheet1.Rows.Count
returns this number dependent on the version.or the equivalent but shorter
This searches up from the bottom of column A for the first non-empty cell, and gets its row number.
This also works if you have data that go further down in other columns. So for instance, if you take your example data and also write something in cell FY4763, the above will still correctly return 9 (not 4763, which any method involving the
UsedRange
property would incorrectly return).Note that really, if you want the cell reference, you should just use the following. You don't have to first get the row number, and then build the cell reference.
Note that this method fails in certain edge cases:
So watch out if you're planning to use row 1,048,576 for these things!