2017-01-16 598 views
1

我在寫一個利用Microsoft.Office.Interop.Excel程序集的類。它是一個「一站式」DLL庫的一部分,將用於java解決方案(限制java端的接口數量)。無法將類型爲'System .__ ComObject'的COM對象轉換爲接口類型'Microsoft.Office.Interop.Excel.Worksheets'

我收到以下錯誤:

Additional information: Unable to cast COM object of type 'System.__ComObject' to interface type 'Microsoft.Office.Interop.Excel.Worksheets'. This operation failed because the QueryInterface call on the COM component for the interface with IID '{000208B1-0000-0000-C000-000000000046}' failed due to the following error: No such interface supported (Exception from HRESULT: 0x80004002 (E_NOINTERFACE)).

這是由下面的代碼拋出:

Public Class XL 

    Public XL As Excel.Application = Nothing 
    Public XLN As String 
    Public WBS As Excel.Workbooks = Nothing 
    Public WBSN() As String 
    Public WB As Excel._Workbook = Nothing 
    Public WBN As String 
    Public WSS As Excel.Worksheets = Nothing 
    Public WSSN() As String 
    Public WS As Excel._Worksheet = Nothing 
    Public WSN As String 
    Public XLCelllValue As Object = Nothing 

    Public Sub New() 

     XL = New Excel.Application() 
     XL.Visible = True 

     WBS = XL.Workbooks 
     WB = WBS.Add() 

     WSS = WB.Worksheets '<this is the line that throws the exception 
     WS = WSS(1) 

    End Sub 
End Class 

我不知道我做錯了所有的屬性定義爲public ,Worksheets是一個有效的集合,WB屬性類型爲Excel._workbook,WSS屬性類型爲Excel.worksheets。

任何想法我失蹤?

+0

作爲我遇到的答案的補充[爲什麼不能從Excel互操作中設置對象?](http://stackoverflow.com/questions/2695229/why-cant-set-cast-an-對象來自excel-interop)和[Excel互操作:_Worksheet或Worksheet?](http://stackoverflow.com/questions/1051464/excel-interop-worksheet-or-worksheet)這可能對你有用。 – Bugs

回答

0

使用Sheets實例:

The Sheets collection can contain Chart or Worksheet objects. The Sheets collection is useful when you want to return sheets of any type. If you need to work with sheets of only one type, see the object topic for that sheet type.

考慮到這一點改變如下聲明:

Public WSS As Excel.Worksheets = Nothing 

要:

Public WSS As Excel.Sheets = Nothing 

另外我也注意到,您正在使用_Workbook_Worksheet不具有訪問DocEvents_Event成員。

您應該考慮使用Workbook_Workbook繼承和Worksheet_Worksheet繼承。無論WorksheetWorkbookDocEvents_Event這給您訪問以下成員繼承:

enter image description here

這隻會如果你想使用的處理程序,但認爲這是值得注意的問題。

最後,在較小的筆記上,您應該打開Option Strict On。這將有助於編寫更好的代碼並在編譯時生成潛在的運行時錯誤。既然這樣,這種代碼WS = WSS(1),與選項嚴格上,將創建下列編譯錯誤:

Option Strict On disallows implicit conversions from 'Object' to 'Microsoft.Office.Interop.Excel.Worksheet'.

通常情況下,編譯器會提示修復,在這種情況下,修復將是:

WS = CType(WSS(1), Excel.Worksheet) 

在你的情況下,這可能不會創建運行時錯誤,但是通過使用Option Strict On,你可以爲自己節省很多痛苦。

+1

作品幫助謝謝@ Jinx88909 – Sylwester

+1

不錯的。很好的答案@ Jink88909 –

0

這是一種混合。

WB.Worksheets返回Sheets

集合所以你需要

Dim WSS As Excel.Sheets = Nothing 
相關問題