简体   繁体   English

VBA中的数组公式错误

[英]Error with array formula in VBA

 A      B    C   D  
east    1   56
west    5   98
east    1   78
west    5   99
south   3   23
east    2   45
south   3   67

I want to get the maximum value of same combination of A+B concatenated. 我想获得串联的A + B相同组合的最大值。 Ex- for east1, I should get 78 in column D. For this I am using VBA, but the code doesn't seem to work. 例如,对于east1,我应该在D列中得到78。为此,我使用的是VBA,但是代码似乎不起作用。 I am using array formula for it. 我正在使用数组公式。

My code is: 我的代码是:

.Range("D2:D" & OutputLastRow).FormulaArray = "=MAX(("$A$2:$A$" & OutputLastRow=A2)*("$B$2:$B$" & OutputLastRow=B2)*("$C$2:$C$" & OutputLastRow))"

The code is running without any bug but the result comes out to be wrong because the cell A2 as well as B2 is not getting updated as the formula moves down from D2. 代码正在运行,没有任何错误,但是结果出了问题,因为随着公式从D2向下移动,单元格A2和B2都没有更新。 A2 remains as A2 and B2 as B2. A2保持为A2,B2保持为B2。 I have tried it using loop but that also doesn't work. 我已经尝试过使用循环,但这也行不通。

When using .FormulaArray on a multi-cell range, it's not like putting an array formula in the first cell and auto-filling. 在多单元格区域上使用.FormulaArray时,这不像将数组公式放在第一个单元格中并自动填充。 You should rather do it explicitly, in two steps. 您应该分两步明确地执行此操作。 Your code, after some corrections, should be like this: 经过更正后,您的代码应如下所示:

' 1- Enter the array formula in top cell
Range("D2").FormulaArray = _
  "=MAX(($A$2:$A$" & OutputLastRow & "=A2)*($B$2:$B$" & OutputLastRow & _
  "=B2)*($C$2:$C$" & OutputLastRow & "))"

' 2- Then autofill down the column
Range("D2:D" & OutputLastRow).FillDown 

Alternatively, you could use the AGGREGATE function to make a "normal" formula which is exactly equivalent to yours: 另外,您可以使用AGGREGATE函数来制作一个与您的公式完全等效的“普通”公式:

Range("D2:D" & OutputLastRow).Formula = _
  "=Aggregate(14, 6, ($A$2:$A$" & OutputLastRow & "=A2)*($B$2:$B$" & OutputLastRow & _
  "=B2)*($C$2:$C$" & OutputLastRow & "), 1)"

You don't really need VBA for this. 您实际上并不需要VBA。 In D1 enter the following array formula (using Ctrl+Shift+Enter instead of just Enter) and drag it down D1输入以下数组公式(使用Ctrl + Shift + Enter而不是Enter),然后将其向下拖动

=MAX(IF(A1&B1=$A$1:$A$7&$B$1:$B$7,$C$1:$C$7))

Your output should look like this: 您的输出应如下所示:

在此处输入图片说明

The formula works because MAX and MIN ignore the FALSE values for A1&B1 = $A$1:$A$7&$B$1:$B$7 and operate only on the remaining results. 该公式起作用是因为MAX和MIN忽略A1&B1 = $A$1:$A$7&$B$1:$B$7的FALSE值,并且仅对其余结果进行运算。 The array formula makes it so that the A1&B1 gets compared to the "current row" value for $A$1:$A$7&$B$1:$B$7 . 数组公式使得A1&B1$A$1:$A$7&$B$1:$B$7的“当前行”值进行比较。 I guess you could lock columns for $A1&$B1 like that but in your example it wasn't necessary. 我想您可以像这样锁定$A1&$B1列,但是在您的示例中,这不是必需的。

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

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