1

下面的代码返回一个数组。我想在电子表格中使用它作为 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
4

3 回答 3

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
于 2013-08-28T19:21:40.283 回答
1

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

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

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

于 2013-08-28T17:19:39.673 回答
0
=INDEX(LoadNumbers(1,10),ROWS($A$1:$A1),COLUMNS($B$1,B$1))
于 2013-08-28T17:40:47.303 回答