繁体   English   中英

将 Excel 公式转换为 VBA

[英]Convert Excel Formula to VBA

我有这个公式,它查看跨多列的各种条件,并检查是否所有条件都匹配,它会将数据从一列粘贴到另一列。 我已经尝试了几种方法将其导入 VBA,但似乎无法正常工作。 谢谢!

=INDEX($D$2:$D$1112,MATCH(1,($A$2:$A$1112=$U$7)*($C$2:$C$1112=$W$7)*($B$2:$B$1112=F3),0))

您将无法使用该数组公式直接将值返回到单元格。 VBA 不会像工作表那样处理数组公式。 最好的方法是使用工作表的处理或 应用程序评估方法之一。

您缺少可供参考的工作表让我很烦恼。 当公式位于工作表单元格中时,它知道它在哪个工作表上。 在 VBA 中使用公式时,父工作表是没有明确工作表引用的“最佳猜测”。

以下是将数组公式的结果放入活动工作表上的 Z2:Z4 的三种方法。 请记住,应修改这些单元格引用以包含工作表名称。

With ActiveSheet
    'this simply puts the formula into the worksheet then reverts the cell from the formula to the returned formula value
    .Range("Z2").FormulaArray = "=INDEX($D$2:$D$1112, MATCH(1, ($A$2:$A$1112=$U$7)*($C$2:$C$1112=$W$7)*($B$2:$B$1112=F3), 0))"
    .Range("Z2") = .Range("Z2").Value

    'this uses the 'square bracket' method of evaluating a formula on-the-fly
    'the formula being evaluated can be array or non-array
    'this method is does not like building a formula string from pieces of text
    .Range("Z3") = [INDEX($D$2:$D$1112, MATCH(1, ($A$2:$A$1112=$U$7)*($C$2:$C$1112=$W$7)*($B$2:$B$1112=F3), 0))]

    'similar to the method directly above, Application.Evaluate does just that.
    'the formula being evaluated can be array or non-array
    'this method is easier to build a formula string from pieces of text
    .Range("Z4") = Application.Evaluate("INDEX($D$2:$D$1112, MATCH(1, ($A$2:$A$1112=$U$7)*($C$2:$C$1112=$W$7)*($B$2:$B$1112=F3), 0))")
End With

您需要进行 2 次更改:

(1) 要在本地 Excel 中可用的 VBA 中使用函数,您需要在每个函数前加上 Application.WorksheetFunction。 IE:

x = Application.WorksheetFunction.Sum(y,z)

(2) 要引用工作表中的单元格,在 VBA 中,您需要通过以下几种方式之一专门访问它。 对我们而言,最简单的是 RANGE 属性,如下所示:

x = Application.WorksheetFunction.Sum(Range("A1:A2"))

因此,要将这两个更改放在一起,您的公式将如下所示:

=Application.WorksheetFunction.INDEX(Range("$D$2:$D$1112",Application.WorksheetFunction.MATCH(1,(RANGE("$A$2:$A$1112"=RANGE("$U$7")*(Range("$C$2:$C$1112"=Range("$W$7")*(Range("$B$2:$B$1112"=Range("F3"),0))

虽然我现在看到你似乎在使用数组公式 - 不确定是否需要任何特殊的夹具才能使其工作。

暂无
暂无

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

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