如何在vb.net中强制转换Microsoft.Office.Interop.Excel.Application.Run



我有以下代码:

Dim technologyMapping = oXL.Run("GetTechnologyMapping")

结果是一个对象。在我的VBA(宏)代码中,我返回一个Collection,如下所示:

Public Function GetTechnologyMapping() As Collection
    ' ...
    Set GetTechnologyMapping = result
End Function

我正在尝试通过CTypeCTypeDynamic进行投角,但到目前为止运气不错。每次代码抛出Exception时,我都无法强制转换此对象,尽管该对象具有属性Count。如何将此对象强制转换为集合?

您可以将VBA.Collection强制转换为System.Collections.IEnumerable。这将允许您使用For Each循环枚举集合。

类似这样的东西:

Sub Test(wbPath As String)
    Dim app As New Excel.Application
    Dim wb As Excel.Workbook = app.Workbooks.Open(wbPath)
    Dim result As Object = app.Run("ReturnCollection")
    wb.Close(Excel.XlSaveAction.xlDoNotSaveChanges)
    app.Quit()
    Dim colAsIEnumerable As System.Collections.IEnumerable = TryCast(result, System.Collections.IEnumerable)
    If colAsIEnumerable IsNot Nothing Then
        For Each o As Object In colAsIEnumerable
            If o IsNot Nothing Then Debug.Print(o.ToString())
        Next
    End If
End Sub

相关内容

最新更新