无法将类型 'System.__ComObject' 的 COM 对象转换为接口类型 'Microsoft.Office.Interop.Excel.Worksheets'

Unable to cast COM object of type 'System.__ComObject' to interface type 'Microsoft.Office.Interop.Excel.Worksheets'

我正在编写一个使用 Microsoft.Office.Interop.Excel 程序集的 class。它是 "one stop shop" DLL 库的一部分,将在 java 解决方案中使用(以限制 java 端的接口数量)。

我收到以下错误:

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.

知道我遗漏了什么吗?

这是一个类型混淆。

WB.Worksheetsreturns合集Sheets

所以你需要

    Dim WSS As Excel.Sheets = Nothing

使用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 and _Worksheet which do not have access to the DocEvents_Event 成员。

您应该考虑使用继承自 _WorksheetWorkbook which inherits from _Workbook and WorksheetWorksheetWorkbook 都继承自 DocEvents_Event,这使您可以访问以下成员:

这仅在您想使用处理程序但认为值得注意时才重要。

最后,在较小的音符上,您应该转动 Option Strict On。这将帮助您编写更好的代码并在编译时产生潜在的运行时错误。就目前而言,这种代码 WS = WSS(1),在 Option Strict On 的情况下,将产生以下编译错误:

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

编译器通常会建议修复,在这种情况下,修复将是:

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

在您的情况下,这可能不会产生运行时错误,但是通过启用 Option Strict,您可以避免很多麻烦。