将数组传递给函数或子过程

时间:2015-07-26 04:11:12

标签: arrays vba

我有一个关于编码到vba的快速问题,我正在尝试将一个排序算法写入vba。

但是我将整数数组传递给函数时遇到了麻烦。有没有办法将数组传递给函数?我认为将它作为变体传递是正确的方法。

还有一种方法可以将函数返回值作为数组传递吗?

1 个答案:

答案 0 :(得分:0)

根据Chip Pearson's examples您可以将数组作为参数传递

Function SumArray(Arr() As Long) As Long
    '''''''''''''''''''''''''''''''''''''''''''
    ' SumArray
    ' This sums the elements of Arr and returns
    ' the total.
    ''''''''''''''''''''''''''''''''''''''''''' 
    Dim N As Long
    Dim Total As Long
    For N = LBound(Arr) To UBound(Arr)
        Total = Total + Arr(N)
    Next N
    SumArray = Total
End Function

同样,返回一个数组作为函数的结果,例如

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.
    ''''''''''''''''''''''''''''''''''''''''
    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

    LoadNumbers = ResultArray()

End Function

更多信息/示例www.cpearson.com