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 am 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?
I was looking for a way to mimic the CTRL+Shift+End, so dotNET solution is great, except with my Excel 2010 I need to add a
set
if I want to avoid an error:and how to check this for yourself:
Here, A65536 is the last cell in the Column A this code was tested on excel 2003.
I would add to the answer given by Siddarth Rout to say that the CountA call can be skipped by having Find return a Range object, instead of a row number, and then test the returned Range object to see if it is Nothing (blank worksheet).
Also, I would have my version of any LastRow procedure return a zero for a blank worksheet, then I can know it is blank.
For the last 3+ years these are the functions that I am using for finding last row and last column per defined column(for row) and row(for column):
Last Column:
Last Row:
For the case of the OP, this is the way to get the last row in column
E
:Debug.Print lastRow(columnToCheck:=Range("E4:E48").Column)
Last Row, counting empty rows with data:
Here we may use the well-known Excel formulas, which give us the last row of a worksheet in Excel, without involving VBA -
=IFERROR(LOOKUP(2,1/(NOT(ISBLANK(A:A))),ROW(A:A)),0)
In order to put this in VBA and not to write anything in Excel, using the parameters for the latter functions, something like this could be in mind:
One important note to keep in mind when using the solution ...
... is to ensure that your
LastRow
variable is ofLong
type:Otherwise you will end up getting OVERFLOW errors in certain situations in .XLSX workbooks
This is my encapsulated function that I drop in to various code uses.