VBA 的数组公式,带或不带。动态范围的数组公式

Array Formula via VBA with or without .ArrayFormula For Dynamic Range

我正在尝试翻译以前在 Excel sheet 上没有 VBA 完成的程序。

这将插入一个数组公式:

={MAX(IF(C2:C355=C2,F2:F355))} into cell CE2

并向下拖到数据集的底部,这是可变的。

我尝试了不同的选项循环遍历可变数据集,例如:

Dim i As Variant
LastRow = Worksheets("Sheet1").Range("A" & Rows.Count).End(xlUp).Row

For i = 2 To LastRow

    Cells(i, 83).FormulaArray = "=MAX(IF(cells(2,LastRow)= cells(5,i),cells(2,LastRow))"

Next i

以下代码似乎有效,但我尝试将代码放入动态循环中导致错误:

Range("CE2").FormulaArray = "=MAX(IF(C:C=C2,F:F))"

通常错误是:

"Unable to set the FormulaArray property of the range class".

我注意到通过 VBA 放置在 sheet 上的数组公式很慢。我猜想有一种方法可以通过不使用 .VarriantArray.

的 VBA 获得与我的公式相同的结果

我研究了 MAX 函数。

我怎么

  1. 循环动态数组并将我的数组公式放在 sheet?

  2. 使用 VBA 函数而不是 .ArrayFormula?

    获得与我的数组公式相同的结果

您似乎将 Cells 的行和列颠倒了,所以我猜您想要:

Cells(i, 83).FormulaArray = "=MAX(IF(R2C3:R" & LastRow & "C3=R[0]C3,R2C5:R" & LastRow & "C5))"

这没有使用 FillDown 的循环:

Dim LastRow As Long
With Worksheets("Sheet1")
    LastRow = .Range("A" & .Rows.Count).End(xlUp).row
    .Cells(2, 83).FormulaArray = "=MAX(IF(" & .Range(.Cells(2, 3), .Cells(LastRow, 3)).Address(1, 1) & "=C2," & .Range(.Cells(2, 6), .Cells(LastRow, 6)).Address(1, 1) & "))"
    .Range(.Cells(2, 83), .Cells(LastRow, 83)).FillDown
End With