Find the last used row in Excel with C#

Harving picture Harving · Sep 5, 2012 · Viewed 34.4k times · Source

Possible Duplicate:
How to get the range of occupied cells in excel sheet

Im trying to find the last used row in an Excel worksheet. For doing this, I'm using this code:

int lastUsedRow = currentWS.Cells.SpecialCells(Excel.XlCellType.xlCellTypeLastCell,Type.Missing).Row;

Most of the time it works fine, but sometimes Excel thinks that there's more rows in the sheet than theres suppose to be.

Fx: If I copy data from sheet1, containing 12 rows, to an empty sheet2, then deleting all data in sheet2, by right clicking and press "Delete..." and copy data from sheet3, containing 5 rows, to sheet2, then lastUsedRow will give me the value of 12 which should have been 5.

enter image description here The image example above is suppose to give my the value of 22 as row count, but instead i'll get 634. Notice the scroll bar to the right.

It seems like Excel thinks that some cells are filled even though I just deleted all cells, before copying new data with fewer rows into the sheet.

Are there any way to "resize" the view of the data in the sheet, so that i'll get the right number of used cells or maybe another way to find the number of the last used row?

Thanks.

Answer

lorenz albert picture lorenz albert · Sep 5, 2012

Edit: New Solution

Since Joe provided the correct code to get the last used row.

Worksheet.UsedRange.Row + Worksheet.UsedRange.Rows.Count - 1 

And using the following command to clear content and formattings

Selection.Delete
Selection.ClearFormats

This should work ;)