Excel VBA - 如何添加动态数组公式

Excel VBA - How to add dynamic array formula

我正在通过 VBA 向工作表添加一个公式,它应该是:

=UNIQUE(IF(TableA[ColumnA]=A1,TableA[ColumnB],""))

这利用 Excel 中的新 SPILL 功能为我提供 B 列值列表,其中 A 列中的相关值与单元格 A 中的值相匹配。我还应用了 UNIQUE 函数来删除任何多个空白 ("") 结果。

如果我手动将公式输入 Excel,这将非常有效,但是在使用 VBA 添加公式时,Excel 在公式中添加 @ 符号,并导致它显示#VALUE!

用于添加公式的 VBA 行是:

=Cells(x,y).Formula = "=UNIQUE(IF(TableA[ColumnA]=A1,TableA[ColumnB],""""))"

Excel 中的结果输出是:

=@UNIQUE(IF(TableA[@[ColumnA]]=A1,TableA[ColumnB],""))

这是怎么回事,我错过了什么?

提前致谢!

好问题,我查了一下...


简而言之:

使用=Cells(x,y).Formula2代替=Cells(x,y).Formula


解释:

表示的@称为隐式交集运算符。来自 MS 文档:

Implicit intersection logic reduces many values to a single value. Excel did this to force a formula to return a single value, since a cell could only contain a single value. If your formula was returning a single value, then implicit intersection did nothing (even though it was technically being done in the background).

但为什么它会出现在您较新的 Excel O365 中?好吧,Range.Formula 使用 IIE(隐式交集),因此添加 @ 基本上可以撤消动态数组功能。 UNIQUE is a new dynamic array function. So, to write this out in code, you should use the Range.Formula2 property (or Range.Formula2R1C1 如果您使用 R1C1 表示法)。这些属性使用 AE(数组求值)并且现在是默认值。

  • Here 是 MS 关于这个主题的信息文档,它更详细地解释了 FormulaFormula2 之间的区别。

  • 如果您想了解有关隐式交集运算符的更多信息,请查看 this

  • 我之前回答了另一个问题,其中涉及隐式交集,并提供了一个示例,说明它的实际工作原理 如果有人觉得它有趣的话。