arrays - 电子表格函数中的返回数组

标签 arrays excel 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

最佳答案

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

现在,您不能让 UDF 根据其输入自动调整范围调用的范围(至少在没有一些丑陋的 Application.OnTime hack 的情况下) ),但无论如何您都不需要这样做。只需将函数放在 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

关于arrays - 电子表格函数中的返回数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18494156/

相关文章:

vba - 复制并粘贴值而不是公式

javascript - ASP.Net MVC 中的 Excel 文件

PHP 函数不返回结果

python - 将单个字母代码连同链编号一起转换为 3 个字母代码

php - 我的 IF 语句有问题

javascript - 我们可以像 PHP implode ('separator' , $array) 一样对 Javascript 数组进行字符串化吗?

c - 如何更改存储在结构体中的 VLA 中的值

excel - VBA提取字符串中的所有字段名

C++函数返回值存储变量问题

c - C中简单平均计算的错误值输出