Tuesday, January 19, 2010

Last cell in range

To get last cell in ActiveSheet you can use this code:

Set LastCell = ActiveSheet.SpecialCells(xlLastCell)

This code works in most cases. But you could face a problem when data was inserted and deleted at the end of sheet. As an example if you clear 5 of 10 filled rows on the sheet, SpecialCells(xlLastCell) will not be changed. It will point to 10th row instead of 5th.
To get last cell of non-empty row you need to use this code:

Sample:
Set LastCell = ActiveSheet.UsedRange.SpecialCells(xlLastCell)

Worksheet.UsedRange is object of Range class which contains filled cells only.

No comments:

Post a Comment