I speculate that the cause of the error may be loops.
Suppose there are three rows of data, and the last two rows meet the conditions, then Rows should be 3.
The condition is met when we loop to the second row. After we delete this row, there are only two rows of data left, and the third row becomes the second row, but the loop will make it continue to look for the third row of data, causing an error.
Try to loop in reverse order.
for (int i = rows; i >1; i--)
{
var temp = ((Range)worksheet.Cells[i, 2]).Value2;
var DepDel = temp.ToString();
Range r = worksheet.Range[worksheet.Cells[i, 1], worksheet.Cells[i, 3]];
if (DepDel == "1")
{
r.EntireRow.Delete(XlDeleteShiftDirection.xlShiftUp);
}
}
If the response is helpful, please click "Accept Answer" and upvote it.
Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.