繁体   English   中英

Excel COM对象强制转换错误

[英]Excel COM Object Cast Error

我试图在代码中避免使用“双点”表示法(请参阅如何正确清理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)).'

任何帮助表示赞赏。

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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