2014-09-29 108 views
0

我試圖避免在我的代碼中使用「雙點」符號(請參閱How do I properly clean up Excel interop objects?)。不過,我得到一個錯誤,當我嘗試下面的代碼Excel COM對象鑄造錯誤

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

您必須聲明Sheet類型的新變量。 oS的類型爲Sheets,而oS.Sheets[os.Count]的類型爲Sheet(不含最終的')。由於從運行時的角度來看這些是不相關的類型,所以您必須聲明一個適當類型的中間變量Sheet

+1

沒有'Sheet'類型,但是'Worksheet'工作。 – kaoao 2014-09-29 15:06:30

+0

感謝您的反饋 – Seb 2014-09-29 15:24:27