Excel COM对象转换错误

时间:2014-09-29 14:26:51

标签: c# excel garbage-collection

我试图避免在我的代码中使用“双点”表示法(请参阅How do I properly clean up Excel interop objects?)。但是,当我尝试更改以下代码时出现错误

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

感谢任何帮助。

1 个答案:

答案 0 :(得分:1)

您必须声明类型为Sheet的新变量。 oS的类型为Sheets,而oS.Sheets[os.Count]的类型为Sheet(没有最终的')。从运行时的角度来看,这些是不相关的类型,您必须声明一个具有适当类型Sheet的中间变量。