简体   繁体   English

在 Office 365 中,如何使用 VBA 在工作表中正确溢出和呈现 Excel 数组 function

[英]In Office 365, How to get an Excel array function to spill and render properly in the worksheet using VBA

With Excel 2019 and Office 365, MS introduced changes to array functions such that they are at least a bit less rigid.在 Excel 2019 和 Office 365 中,MS 对数组函数进行了更改,使其至少不那么严格。

Suppose I have the following VBA function假设我有以下 VBA function

Public Function fooo(a As Integer, b As Integer) As Variant
    Dim mat() As Integer
    ReDim mat(0 To a - 1, 0 To b - 1) As Integer
    Dim i As Integer
    Dim j As Integer
    For i = 0 To a - 1
        For j = 0 To b - 1
            mat(i, j) = a
        Next j
    Next i
    fooo = mat
End Function

and go into a sheet and type =fooo(4,4) into a cell.和 go 到工作表中,然后在单元格中键入=fooo(4,4) All I have to do is press enter, not control-shift-enter, and Excel executes my array function, leaving me an 4 x 4 array of 4s.我所要做的就是按 Enter,而不是 control-shift-enter,然后 Excel 执行我的数组 function,给我留下一个 4 x 4 的 4 数组。 So far so good.到目前为止,一切都很好。

Now if I try the following from VBA现在,如果我从 VBA 尝试以下操作

Public Sub tryit()
    Range("a40").FormulaArray = "=fooo(3,10)"
    Range("a40").Calculate
End Sub

I see a 3 in cell a40, but not the rest of the matrix.我在单元格 a40 中看到 3,但没有看到矩阵的 rest。 Only when I click on the cell and press enter does the rest of the matrix appear.只有当我单击单元格并按 Enter 时,矩阵的 rest 才会出现。

Moving right along, I can now try something like this继续前进,我现在可以尝试这样的事情

Public Sub tryit2()
    Dim i As Integer
    For i = 1 To 10
        Range("a40").FormulaArray = "=fooo(" & (i + 3) & "," & (i + 3) & ")"
        Application.Wait Now + TimeValue("0:00:01")
    Next i
End Sub

If cell a40 contains the matrix from before, this code happily overwrites the matrix there already.如果单元格 a40 包含之前的矩阵,则此代码会愉快地覆盖那里的矩阵。 Yeah, sure, there are some #N/As, but I can live with that.是的,当然,有一些#N/As,但我可以忍受。 But if that cell was previously fresh, Excel only shows that first number.但是,如果该单元格以前是新鲜的,则 Excel 仅显示第一个数字。

It almost looks like Excel pre-allocates a block of cells for the result, just not with VBA.它几乎看起来像 Excel 为结果预分配了一个单元块,而不是 VBA。

How can I get that initial array function to display from VBA?如何让初始数组 function 从 VBA 显示?

In tryit , use Formula2 instead of FormulaArray .tryit中,使用Formula2而不是FormulaArray

From the docs :文档

Formulas set using Range.Formula2 will always be evaluated as an array and may spill if more than 1 result is returned.使用Range.Formula2设置的公式将始终作为数组进行评估,如果返回超过 1 个结果,则可能会溢出。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM