Question

 foreach (Excel.Worksheet sheet in m_objExcel.Sheets)
 {
     if (sheet.Name == "Before & After Lube Weight")
     {
         //sheet.Delete();
         (Excel.Worksheet)m_objExcel.Sheets[6]).Delete();

         m_objSheet = (Excel.Worksheet)m_objSheets.Add(m_objSheets[6], Type.Missing, Type.Missing, Type.Missing);
         m_objSheet.Name = "Before & After Lube Weight";
     }
}

The code above are use to overwrite an existing worksheet with new worksheet. I have tried to debug line by line and all the code is working well but worksheet never gets deleted before adding another sheet with the same name (Noted Framework 2.0).

The exception message occurs

ERROR: CANNOT RENAME THE SHEET TO THE SAME NAME AS ANOTHER SHEET

I believe that it's because the previous worksheet is not properly deleted.

Was it helpful?

Solution

Your current solution seems inefficient to me... It sounds like all you're trying to do is clear your sheet....

Try deleting Cells...

foreach (Excel.Worksheet sheet in m_objExcel.Sheets)
 {
     if (sheet.Name == "Before & After Lube Weight")
     {
         sheet.Cells.Delete();
     }
}

If still, you want to delete your sheet then remember this is a bad approach...

(Excel.Worksheet)m_objExcel.Sheets[6]).Delete();

You don't need to iterate over a collection if you're using this method to delete the sheet. If some sheets have been added or deleted your collections index may shift so your suspected 6th sheet may no longer be there etc...

The correct approach is (not sure why it's commented in your code)

sheet.Delete();
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top