将数组从VBA传递到VB.NET

我正在使用vb.net COM互操作在Microsoft Excel中工作,我无法将数组从vb传递到vb.net.我在vb.net代码中有一个PointPairs属性,我需要从vb设置,我在传递二维数组时遇到问题.我已经尝试使用2D数组显式设置属性以及将两个1D数组传递给Sub以尝试在vb.net中设置属性,但我尝试过的任何内容似乎都无法工作.

vb.net代码:

Public Property PointPairs() As Double(,)
   Get
     ...
     Return array
   End Get
   Set(ByVal Value(,) As Double)
     ...
   End Set
End Property

Public Sub SetPointPairs(ByRef spline As Spline, ByRef xValues() As Double, _
                              ByRef yValues() As Double)
   Dim Value(,) As Double
   ReDim Value(1, UBound(xValues, 1))

   For i As Integer = 0 To UBound(xValues, 1)
       Value(0, i) = xValues(i)
       Value(1, i) = yValues(i)
   Next

   spline.PointPairs = Value
End Sub

vb代码:

Dim spline1 As New Spline
Dim points(), xValues(), yValues() As Double
'read input from excel cells into points() array/add x and y values to respective arrays

spline1.PointPairs = points 'first method (doesn't work)
Call SetPointPairs(spline1, xValues, yValues)  'second method (doesn't work)

所有东西都被vb.net正确导出,属性/ subs / functions在vba中的对象浏览器中可见,但是当我尝试在这两种方法中传递数组时,我得到错误消息函数或接口标记为限制,或者函数使用Visual Basic中未支持的自动化类型或未定义的Sub或Function.我也尝试过使用< MarshalAs()>但我以前从未使用它,也找不到很多关于如何使用它来在vb和vb.net之间传递数组的文档.

提前感谢任何建议或解决方案

最佳答案 对于任何对该解决方案感兴趣的人,我发现这篇文章正是我所需要的.

http://www.codeproject.com/Articles/12386/Sending-an-array-of-doubles-from-Excel-VBA-to-C-us?fid=247508&select=2478365&tid=2478365

我不得不将2D数组分解为VBA中的两个一维双打数组,并将它们作为对象传递给vb.net,并按照文章中的描述进行修改.我更改了SetPointPairs Sub,如下所示,并添加了这个私有函数,以便在.net代码中从Object转换为Array

Sub SetPointPairs(ByRef spline As CubicSpline, ByRef xValues As Object, ByRef yValues As Object) Implements iCubicSpline.SetPointPairs

        Dim xDbls(), yDbls(), pointDbls(,) As Double

        xDbls = ComObjectToDoubleArray(xValues)
        yDbls = ComObjectToDoubleArray(yValues)
        ReDim pointDbls(1, UBound(xDbls, 1))
        For i As Integer = 0 To UBound(pointDbls, 2)
            pointDbls(0, i) = xDbls(i)
            pointDbls(1, i) = yDbls(i)
        Next

        spline.PointPairs = pointDbls

End Sub

Private Function ComObjectToDoubleArray(ByVal comObject As Object) As Double()

        Dim thisType As Type = comObject.GetType
        Dim dblType As Type = Type.GetType("System.Double[]")
        Dim dblArray(0) As Double

        If thisType Is dblType Then
            Dim args(0) As Object
            Dim numEntries As Integer = CInt(thisType.InvokeMember("Length", BindingFlags.GetProperty, _
                                            Nothing, comObject, Nothing))
            ReDim dblArray(numEntries - 1)
            For j As Integer = 0 To numEntries - 1
                args(0) = j
                dblArray(j) = CDbl(thisType.InvokeMember("GetValue", BindingFlags.InvokeMethod, _
                                        Nothing, comObject, args))
            Next
        End If

        Return dblArray

    End Function
点赞