Tuesday, January 1, 2013

Finding last row or rightmost column


Problem definition:
Many times we have to get the last row or the rightmost column of data in a table.
This may be to loop within the table rows/columns or to copy one or more rows or columns or for any other purpose.


Mechanism:
get the last cell in the row or column
get the end in upward(for last row) or lef(for last column) direction

In VBA:
To get the last row

Code below returns the cell in last row in column c. In this code, "ws" is a worksheet object that is set to any worksheet. This worksheet may be in the current active workbook or any OPEN workbook that may not be active. The worksheet itself may or may not be the active sheet.

ws.cells(rows.count,c).end(xlup)

'end' is actually a property used on a range and it returns a range object.
So it can be made useful by capturing it in a variable of type range.

dim rng as range
set rng = ws.cells(rows.count,c).end(xlup)

rows.count gives the total number of rows on any worksheet. this value is version dependent.
Since row numbers start from 1 value returned by rows.count is the number of the last row.

Read here how to find the version of xl

Getting the row number is now easy
dim rw as integer
rw = rng.row

To get the address of the last cell
dim strAdd as string
strAdd = rng.address

If we are not going to use the returned cell object for any other purpose we can save memory and coding as follows:

rw = ws.cells(rows.count,c).end(xlup).row
strAdd = ws.cells(rows.count,c).end(xlup).address

No comments:

Post a Comment