0

I'm trying to avoid "double dot" notation in my code (see How do I properly clean up Excel interop objects?). However, I get an error when I try to change the following code

Excel.Workbook oWB;
...
oWB.Sheets[oWB.Sheets.Count].Delete();
oWB.Sheets[oWB.Sheets.Count].Delete();
oWB.Sheets[oWB.Sheets.Count].Delete();

to this

Excel.Sheets oS;
oS = oWB.Sheets;
//error occurs in the following line
oS = oWB.Sheets[oS.Count];
oS.Delete();
oS.Delete();
os.Delete();

The error is 'Unable to cast COM object of type 'System.__ComObject' to interface type 'Microsoft.Office.Interop.Excel.Sheets'. This operation failed because the QueryInterface call on the COM component for the interface with IID '{000208D7-0000-0000-C000-000000000046}' failed due to the following error: No such interface supported (Exception from HRESULT: 0x80004002 (E_NOINTERFACE)).'

Any help is appreciated.

Community
  • 1
  • 1
kaoao
  • 37
  • 7

1 Answers1

1

You have to declare a new variable of type Sheet. oS is of type Sheets, while oS.Sheets[os.Count] is of type Sheet (without final 's'). As these are unrelated type from the runtime point of view, you must declare an intermediate variable with appropriate type Sheet.

Seb
  • 2,637
  • 1
  • 17
  • 15