VBA中的数组公式出错

时间:2017-07-22 21:55:57

标签: arrays vba excel-vba excel-formula excel

Structure = {Double factor, Vector position};
Structure[] list = {p, q, u};
for i = 0; i < list.length; i++;
    for j = i+1; j < list.length; j++;
        structureFactor = calculateFactor(list[i], list[j]);
        //Destructive updates
        list[i].position += structureFactor; //Add factor to each vector value
        list[j].position -= structureFactor;

我希望获得A + B连接的相同组合的最大值。对于east1,我应该在D列中获得78.为此我使用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

代码运行没有任何错误,但结果出错了,因为当公式从D2向下移动时,单元格A2和B2没有得到更新。 A2保持为A2,B2保持为B2。我已经尝试过使用循环,但这也没有用。

2 个答案:

答案 0 :(得分:4)

在多单元格范围内使用.FormulaArray时,不像在第一个单元格中放置数组公式并自动填充。您应该分两步明确地执行此操作。经过一些修正后,您的代码应如下所示:

' 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 

或者,您可以使用AGGREGATE函数制作一个与您的完全等效的“普通”公式:

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

答案 1 :(得分:1)

你真的不需要VBA。在D1中输入以下数组公式(使用Ctrl + Shift + Enter而不是Enter)并将其向下拖动

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

您的输出应如下所示:

enter image description here

该公式有效,因为MAX和MIN忽略A1&B1 = $A$1:$A$7&$B$1:$B$7的FALSE值,并仅对剩余的结果进行操作。数组公式使A1&B1$A$1:$A$7&$B$1:$B$7的“当前行”值进行比较。我想你可以锁定$A1&$B1的列,但在你的例子中没有必要。