2017-01-16 1477 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 
相关问题