Excel COM对象铸造错误

我试图避免在我的代码中的“双点”符号(请参阅如何正确清理Excel互操作对象? )。 但是,当我尝试更改以下代码时出现错误

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

对此

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

错误是'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)).'

任何帮助表示赞赏。

你必须声明一个types为Sheet的新variables。 oSSheetstypes,而oS.Sheets[os.Count]Sheettypes(没有final)。 由于这些是从运行时的angular度来看是不相关的types,所以您必须声明一个具有适当typesSheet的中间variables。