문제

 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.

도움이 되었습니까?

해결책

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();
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top