Application.Run for Macro返回数组

时间:2018-01-17 16:38:57

标签: excel vba xll

我想调用一个函数" arrayfun1"来自xll-addin的vba中的" Application.Run"

data

这适用于只返回一个输出的函数,但不适用于返回数组的函数。但是,如果我在工作表中使用函数作为Arrayformula它。但我正在寻找一种编程解决方案。

任何想法?

2 个答案:

答案 0 :(得分:0)

我在Chip的网站上找到了这个例子: http://www.cpearson.com/excel/passingandreturningarrays.htm

Sub AAATest()
    Dim Arr() As Long
    Dim N As Long
    Arr = LoadNumbers(Low:=101, High:=110)
    If IsArrayAllocated(Arr:=Arr) = True Then
        For N = LBound(Arr) To UBound(Arr)
           Debug.Print Arr(N)
        Next N
    Else
        ''''''''''''''''''''''''''''''''''''
        ' Code in case Arr is not allocated.
        ''''''''''''''''''''''''''''''''''''
    End If
End Sub

Function LoadNumbers(Low As Long, High As Long) As Long()
    '''''''''''''''''''''''''''''''''''''''
    ' Returns an array of Longs, containing
    ' the numbers from Low to High. The 
    ' number of elements in the returned
    ' array will vary depending on the 
    ' values of Low and High.
    ''''''''''''''''''''''''''''''''''''''''

    '''''''''''''''''''''''''''''''''''''''''
    ' Declare ResultArray as a dynamic array
    ' to be resized based on the values of
    ' Low and High.
    '''''''''''''''''''''''''''''''''''''''''
    Dim ResultArray() As Long
    Dim Ndx As Long
    Dim Val As Long
    '''''''''''''''''''''''''''''''''''''''''
    ' Ensure Low <= High
    '''''''''''''''''''''''''''''''''''''''''
    If Low > High Then
        Exit Function
    End If
    '''''''''''''''''''''''''''''''''''''''''
    ' Resize the array
    '''''''''''''''''''''''''''''''''''''''''
    ReDim ResultArray(1 To (High - Low + 1))
    ''''''''''''''''''''''''''''''''''''''''
    ' Fill the array with values.
    ''''''''''''''''''''''''''''''''''''''''
    Val = Low
    For Ndx = LBound(ResultArray) To UBound(ResultArray)
        ResultArray(Ndx) = Val
        Val = Val + 1
    Next Ndx
    ''''''''''''''''''''''''''''''''''''''''
    ' Return the array.
    ''''''''''''''''''''''''''''''''''''''''
    LoadNumbers = ResultArray()

End Function

答案 1 :(得分:0)

您可以在VBA中使用Declare Function语句调用该函数(尽管您需要获取一些工具来将参数从VBA格式转换为Excel SDK格式,反之亦然,以获得返回值),或使用ExecuteExcel4MacroEvaluate(尽管那些需要先将所有参数转换为字符串)。

请参阅此网页: https://fastexcel.wordpress.com/2014/12/13/calling-xlamxllautomation-udfs-from-vba-evaluate-run-or-reference/

这个问题: How do I call an xll addin function from vba?