简体   繁体   中英

Excel COM Object Cast Error

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)).' '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.

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM