Excel COM对象强制转换错误
本文关键字:转换 错误 COM 对象 Excel | 更新日期: 2023-09-27 18:25:01
我正在努力避免在代码中使用"双点"表示法(请参阅如何正确清理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)).'
感谢您的帮助。
您必须声明一个类型为Sheet
的新变量。oS
属于Sheets
类型,而oS.Sheets[os.Count]
属于Sheet
类型(不带韵母"s")。由于从运行时的角度来看,这些是不相关的类型,因此必须声明一个具有适当类型Sheet
的中间变量。