I’m using UsedRange via the interop excel object in C# to grab the last row of a worksheet. The worksheet is newly created with only the Name property edited. However, when I get the ws.UsedRange.Rows.Count, I get over 10k. Why is this not giving me 0 or 1? How can I get the true last row?
Application xlApp = null;
Worksheet temp;
Range cell;
int row;
int col;
int i;
xlApp = new Application();
xlApp.Visible = true;
Workbook wbDetail = xlApp.Workbooks.Add();
wbDetail.Worksheets.Add(Type.Missing, Type.Missing, 26, XlWBATemplate.xlWBATWorksheet);
i = 0;
while(i < 29)
{
temp = (Worksheet)wbDetail.Worksheets[i+1];
temp.Name = "TITLE_"+i
i++;
}
DateTime reqdate;
i=0;
while(i<29)
{
temp = (Worksheet)wbDetail.Worksheets["TITLE_"+i];
int j = 0;
temp.get_Range("A1", Type.Missing).Value = "TITLE STUFF";
row = temp.UsedRange.Rows.Count;
while(j < 50)
{
cell = (Range)temp.Cells[row+1, j+1];
cell.Value = j;
j++;
}
}
i++
}
wbDetail.Save();
Under certain conditions (not sure what they are), Excel will have “used” rows that don’t have any real values (other than blank, null, etc.).
The way I’ve done this in the past is to load the sheet’s values into an array*, then loop backwards through the rows of the array until one of the columns has a non-blank value.
*- I would HIGHLY recommend not calling
Cells[i,j]within a loop. Load the values in an array and then loop over the array: