问题
I'm running into an Odd problem that I cant seem to find a solution for. I'm trying to delete any work sheet in a workbook that contains a certain worksheet name and I keep getting this exception: "Unable to get the Delete property of the Worksheet class" I'm able to use the worksheet class in other places but when i try to use the Delete(); method, or even the one that sets the visibility of said sheet I get the same thing. Any help as to why would be appreciated!
Microsoft.Office.Interop.Excel.Sheets TestWorksheets = TestBook.Worksheets;
if (TestWorksheets.Count > NumberofsheetsIWantToKeep)
{
int WorkSheetCounter = TestWorksheets.Count;
while (WorkSheetCounter > NumberofsheetsIWantToKeep)
{
if(TestWorksheets[WorkSheetCounter].Name.Contains("blah"))
{
TestWorksheets[WorkSheetCounter].Delete();
}
WorkSheetCounter--;
}
}
回答1:
turns out I had to activate the workbook and the worksheet before I could delete it. I feel silly and apologize for that!
回答2:
use below code instead of directly deleting. Activate workbook and worksheet.
Microsoft.Office.Interop.Excel.Workbook book = TestBook;
book.Activate();
TestWorksheets[WorkSheetCounter].Activate();
TestWorksheets[WorkSheetCounter].Delete();
回答3:
I had a similar issue this morning while processing an XLSX file to clean it of named references and a macro worksheet. When attempting to Delete() the sheet it would fail with error: Exception from HRESULT: 0x800A03EC. Found that even with Document Inspector in Excel could not remove the hidden worksheet. Further investigation led me to discover the sheet's visibility was set to VeryHidden. Changing the visibility to something other than VeryHidden before attempting to delete the worksheet resolved my problem.
Using the original example code from above this is what I needed to get the delete to not error.
Microsoft.Office.Interop.Excel.Sheets TestWorksheets = TestBook.Worksheets;
if (TestWorksheets.Count > NumberofsheetsIWantToKeep)
{
int WorkSheetCounter = TestWorksheets.Count;
while (WorkSheetCounter > NumberofsheetsIWantToKeep)
{
if(TestWorksheets[WorkSheetCounter].Name.Contains("blah"))
{
if(TestWorksheets[WorkSheetCounter].Visible == Microsoft.Office.Interop.Excel.XlSheetVisibility.xlSheetVeryHidden)
{ TestWorksheets[WorkSheetCounter].Visible = Microsoft.Office.Interop.Excel.XlSheetVisibility.xlSheetHidden; }
TestWorksheets[WorkSheetCounter].Delete();
}
WorkSheetCounter--;
}
}
来源:https://stackoverflow.com/questions/39859276/comexception-when-trying-to-delete-a-worksheet-from-an-excel-file-in-c-sharp