简体   繁体   English

通过 VBA 使用或不使用 .ArrayFormula 动态范围的数组公式

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

I am trying to translate a procedure previously done without VBA on an Excel sheet.我正在尝试在 Excel 工作表上翻译以前在没有 VBA 的情况下完成的程序。

This inserts an array formula:这将插入一个数组公式:

={MAX(IF(C2:C355=C2,F2:F355))} into cell CE2 ={MAX(IF(C2:C355=C2,F2:F355))} 进入单元格 CE2

and drag it down to the bottom of the data set, which is variable.并将其向下拖动到数据集的底部,这是可变的。

I have attempted different options looping through a variable data set, such as:我尝试了遍历可变数据集的不同选项,例如:

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

The following code seems to work, but my attempts to work the code into a dynamic loop causes errors:以下代码似乎有效,但我尝试将代码处理为动态循环会导致错误:

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

Often the error is:通常错误是:

"Unable to set the FormulaArray property of the range class". “无法设置范围类的 FormulaArray 属性”。

I have noticed that array formulas placed onto the sheet via VBA are slow.我注意到通过 VBA 放置在工作表上的数组公式很慢。 I am guessing that there is a way to achieve the same result as my formula via VBA that does NOT use .VarriantArray .我猜有一种方法可以通过不使用.VarriantArray VBA 实现与我的公式相同的结果。

I have looked into the MAX function.我研究了 MAX 函数。

How do I我怎么办

  1. Loop through a dynamic array and place my array formula on the sheet?循环遍历动态数组并将我的数组公式放在工作表上?

  2. Achieve the same result as my array formula using VBA functions other than .ArrayFormula ?使用.ArrayFormula以外的 VBA 函数获得与我的数组公式相同的结果?

This without the loops using FillDown:这没有使用 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

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

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

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

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