.Net Excel Interop Deleting a worksheet
After more than one hour looking I found the answer:
xlApp.DisplayAlerts = false;
worksheet.Delete();
xlApp.DisplayAlerts = true;
When dealing with deleting Excel Worksheets, there are two important things to know:
-
Excel interop counts from 1 (and not from zero), therefore, removing the second item will cause the third item to take its place!. so, the proper way to remove worksheets is from the last to the first:
// Remove LAST worksheet MyWorkBook.Worksheets[3].Delete(); // and only then remove the second (which is the last one) MyWorkBook.Worksheets[2].Delete();
alternatively, you can delete the second item ([2]) on the list twice, which will give you the same result.
-
The following line will throw exception when you only got one worksheet left:
MyWorkBook.Worksheets[1].Delete();