簡體   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

在 Excel 2019 和 Office 365 中,MS 對數組函數進行了更改,使其至少不那么嚴格。

假設我有以下 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

和 go 到工作表中,然后在單元格中鍵入=fooo(4,4) 我所要做的就是按 Enter,而不是 control-shift-enter,然后 Excel 執行我的數組 function,給我留下一個 4 x 4 的 4 數組。 到目前為止,一切都很好。

現在,如果我從 VBA 嘗試以下操作

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

我在單元格 a40 中看到 3,但沒有看到矩陣的 rest。 只有當我單擊單元格並按 Enter 時,矩陣的 rest 才會出現。

繼續前進,我現在可以嘗試這樣的事情

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

如果單元格 a40 包含之前的矩陣,則此代碼會愉快地覆蓋那里的矩陣。 是的,當然,有一些#N/As,但我可以忍受。 但是,如果該單元格以前是新鮮的,則 Excel 僅顯示第一個數字。

它幾乎看起來像 Excel 為結果預分配了一個單元塊,而不是 VBA。

如何讓初始數組 function 從 VBA 顯示?

tryit中,使用Formula2而不是FormulaArray

文檔

使用Range.Formula2設置的公式將始終作為數組進行評估,如果返回超過 1 個結果,則可能會溢出。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM