在VB.NET中创建DLL文件并在Excel VBA中使用

时间:2017-05-31 15:51:10

标签: vb.net vba excel-vba dll excel

我在VB.NET中创建了一个DLL文件,我希望在Excel VBA中使用它。当我像一个函数一样使用它时,它工作得很完美,但当我使用带有ByRef变量的sub时,它不起作用,Excel重新启动并出现错误。

VB.NET中的代码是:

Public Function distinctArr(ByVal arr As String()) As String()
        Return arr.ToList.Distinct.ToArray
End Function

Public Sub sortArr(ByVal arr As String(), ByRef a As String())
    Dim tolist As List(Of String) = arr.ToList
    tolist.Sort()
    a = tolist.ToArray
End Sub

这是VBA中的代码:

Dim objMda As Excelcode.mda
Set objMda = New Excelcode.mda
Dim distinc_Item() As String
Dim all_Items() As String
all_Items = rng_to_string(rng_rizmetre)
distinc_Item = objMda.distinctArr(all_Items) '''This line is working perfect
Dim Sorted_Item() As String
objMda.sortArr distinc_Item, Sorted_Item

代码有什么问题?

1 个答案:

答案 0 :(得分:1)

最后我能找到答案。 vb.net中的代码

Public Class MainClass
    Sub sortArr(ByVal arr As String(), ByRef sortedarr As String())
        sortedarr = arr
        Array.Sort(sortedarr)

    End Sub
End Class

和excel vba中的代码:

Sub aaa()
Dim Mycode As excelcode.MainClass
Set Mycode = New excelcode.MainClass
Dim arr(2) As String
arr(0) = "m"
arr(1) = "a"
arr(2) = "d"
Dim sortedArr() As String
ReDim sortedArr(0)
  Mycode.sortArr arr, sortedArr
End Sub

通过这段代码我可以将数组byval传递给vb.net dll然后vb.net传递排序数组。