简体   繁体   中英

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.

Suppose I have the following 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. 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. So far so good.

Now if I try the following from 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. Only when I click on the cell and press enter does the rest of the matrix appear.

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. Yeah, sure, there are some #N/As, but I can live with that. But if that cell was previously fresh, Excel only shows that first number.

It almost looks like Excel pre-allocates a block of cells for the result, just not with VBA.

How can I get that initial array function to display from VBA?

In tryit , use Formula2 instead of 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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