在 VBA UDF 中始终返回整个数组?

Consistently returning the entire array in a VBA UDF?

我已经编写了以下简单的 VBA 函数来计算两个数量之间的线性级数对于一定的时间间隔和 return 作为数组的级数:

Public Function applyLinear(startAmount As Double, stopAmount As Double, Intervals As Integer)
    Dim diff As Double
    Dim resultArr() As Double
    Dim counter As Integer    
    diff = stopAmount - startAmount
    ReDim resultArr(Intervals, 0)
    resultArr(0, 0) = startAmount
    For counter = 1 To (Intervals)
        resultArr(counter, 0) = resultArr(counter - 1, 0) + diff / Intervals
    Next ' counter
    counter = 0
    applyLinear = resultArr
End Function

不幸的是,实际输出到工作表的内容 完全取决于调用上述公式的单元格数量。(这意味着用户应用起来变得容易得可笑功能不正确!)

如何保证整个数组在全部情况下输出到工作表?

编辑:或者更具体地说,当从单个单元格调用上述 UDF 时,如何让 VBA 输出整个数组?

编辑 2:更多说明。如果在调用它时使用 "intervals+1" 行,该函数确实会按预期工作。但是,如果(例如)用户在间隔 > 4 时不小心调用了 4 行的函数,就会出现问题。在这种情况下,只有 resultArr 的前四个元素被输出到工作表,这是一个问题,因为它不会代表完整的线性级数。

在研究如何执行我在上面评论中建议的操作时,我发现了一些关于 Application.Caller 函数的有趣信息,它允许您访问输入 UDF 的单元格的属性。请参阅这里:Excel cell from which a Function is called

根据 cpearson [http://www.cpearson.com/excel/returningarraysfromvba.aspx]

的一些进一步指导,这是一种方法
Public Function applyLinear(startAmount As Double, stopAmount As Double, Intervals As Integer)

Dim diff As Double
Dim resultArr() As Double
Dim counter As Integer
ReDim resultArr(Intervals, 0)

If Application.Caller.Rows.Count <> Intervals + 1 Then

    applyLinear = "ERROR - MUST ENTER THIS FORMULA IN " & Intervals + 1 & " CELLS"

Else

    diff = stopAmount - startAmount
    resultArr(0, 0) = startAmount

    For counter = 1 To (Intervals)
        resultArr(counter, 0) = resultArr(counter - 1, 0) + diff / Intervals
        TotalityCheck = TotalityCheck + resultArr(counter, 0) 'builds in by the end of the loop the total array value
    Next ' counter


    applyLinear = resultArr
End If

End Function

不过,既然您已经使用了 Application.Caller 函数,您或许可以更简单地执行此操作,无需用户输入间隔数 - 相反,定义区间数为application.caller.rows - 1,如下:

Public Function applyLinear(startAmount As Double, stopAmount As Double)

Dim diff As Double
Dim resultArr() As Double
Dim counter As Integer
Dim Intervals As Integer
ReDim resultArr(Intervals, 0)

Intervals = Application.Caller.Rows.Count - 1

    diff = stopAmount - startAmount
    resultArr(0, 0) = startAmount

    For counter = 1 To (Intervals)
        resultArr(counter, 0) = resultArr(counter - 1, 0) + diff / Intervals
        TotalityCheck = TotalityCheck + resultArr(counter, 0) 'builds in by the end of the loop the total array value
    Next ' counter


    applyLinear = resultArr


End Function