如何在vb.net中转换Microsoft.Office.Interop.Excel.Application.Run结果?

时间:2016-07-19 22:30:13

标签: vb.net vba

我有以下代码:

Dim technologyMapping = oXL.Run("GetTechnologyMapping")

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

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

我试图通过CTypeCTypeDynamic进行投射,但到目前为止运气好了。每次代码抛出异常时,我都无法转换此对象,尽管该对象具有属性Count。如何将此对象转换为集合?

1 个答案:

答案 0 :(得分:2)

您可以将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