在电子表格函数中返回数组

时间:2013-08-28 17:11:04

标签: arrays excel-vba return spreadsheet vba

下面的代码返回一个数组。我想在电子表格中使用它作为excel公式来返回数组。但是,当我这样做时,它只返回第一个值到单元格。无论如何返回数组的大小与数组相同?

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

3 个答案:

答案 0 :(得分:5)

UDF当然可以返回一个数组,并且你的函数运行正常。只需选择,例如,范围B2:D2,将=LoadNumbers(1, 3)放入公式栏,然后按Ctrl + Shift + Enter告诉Excel它是一个数组函数。

现在,您不能让UDF根据其输入自动调整调用的范围(至少不是没有一些丑陋的Application.OnTime黑客),但是你不要无论如何都不需要这样做。只需将函数放在1000个单元格的范围内,然后让UDF用空白单元格填充未使用的空格,如下所示:

Function LoadNumbers(ByVal Low As Long, ByVal High As Long) As Variant()
    Dim ResultArray() As Variant
    Dim Ndx As Long
    Dim Val As Long
    Dim SourceCols As Long

    SourceCols = Application.Caller.Columns.Count

    If Low > High Then
        Exit Function
    End If
    If High - Low + 1 > SourceCols Then High = Low + SourceCols - 1

    ReDim ResultArray(1 To SourceCols)

    Val = Low
    For Ndx = LBound(ResultArray) To (High - Low + 1)
        ResultArray(Ndx) = Val
        Val = Val + 1
    Next Ndx
    For Ndx = (High - Low + 2) To UBound(ResultArray)
        ResultArray(Ndx) = vbNullString
    Next Ndx
    LoadNumbers = ResultArray()
End Function

答案 1 :(得分:1)

工作表公式只能将值输出到写入公式的同一个单元格。就目前而言,代码已生成一个数组。如果要在复制公式时显示值,请使用这样的公式(在任何单元格中),然后复制:

=INDEX(LoadNumbers(1,10),ROWS($A$1:$A1))

如果你复制得太远,你会得到#REF!错误,因为LoadNumbers用完了数字。

答案 2 :(得分:0)

=INDEX(LoadNumbers(1,10),ROWS($A$1:$A1),COLUMNS($B$1,B$1))