2013-07-09 93 views
4

我正在使用vb.net COM互操作在Microsoft Excel中工作,而且我無法將數組從vb傳遞到vb.net。我在vb.net代碼中有一個PointPairs屬性,我需要從vb設置,並且無法傳遞2維數組。我已經嘗試使用2D數組顯式設置屬性,並將兩個1D數組傳遞給Sub以嘗試在vb.net中設置屬性,但我沒有試過似乎沒有任何效果。將數組從VBA傳遞到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正確導出和屬性/潛艇/功能是在VBA對象瀏覽器可見,但是當我嘗試在這兩種方法中傳遞數組時,我收到錯誤消息Function or interfaces markes as restricted, or the function uses an automation type not supported in Visual BasicSub or Function not defined。我也嘗試使用<MarshalAs()>,但我從來沒有使用過它,無法找到關於如何使用它在vb和vb.net之間傳遞數組的很多文檔。

預先感謝任何建議或解決方案

回答

2

任何有興趣的解決方案,我發現這篇文章,這是正是我需要的。

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代碼中添加了此私有函數以將對象轉換爲數組。

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 
相關問題