【问题标题】:Writing formula in cell gives error although formula is correct尽管公式正确,但在单元格中写入公式会出错
【发布时间】:2015-12-16 15:19:11
【问题描述】:

我正在使用 VBA 在 MS Excel 工作表中编写公式。当我手动将公式复制到单元格时,它可以工作,但是当我使用下面的行时,它会给我一个运行时错误:

'1004':应用程序定义或对象定义的错误。

ActiveSheet.Cells(Row + 3, Column + i).Formula = "=SUMPRODUCT(--(OFFSET(endResourceNaam;2;0):OFFSET(endResourceNaam;1000;0)=$A" & Row + 1 & ");--(OFFSET(endResourceNaam;2;4):OFFSET(endResourceNaam;1000;4)=$E" & Row + 1 & ");OFFSET(endResourceWeek;2;" & ColumnLetter(Column - 1) & "$1):OFFSET(endResourceWeek;1000;" & ColumnLetter(Column - 1) & "$1))"

生成的(循环中的第一个)字符串是:

=SUMPRODUCT(--(OFFSET(endResourceNaam;2;0):OFFSET(endResourceNaam;1000;0)=$A6);--(OFFSET(endResourceNaam;2;4):OFFSET(endResourceNaam;1000;4)=$E6);OFFSET(endResourceWeek;2;O$1):OFFSET(endResourceWeek;1000;O$1))

我通过从 VBA 代码打印公式来测试公式,然后将其复制/粘贴到单元格中。这样我就可以确定生成的字符串实际上是正确的。据我所知,VBA 中内置了某种保护措施,可确保当我尝试编写公式时,公式正确且有效。该保护中可能有一些东西阻止我将公式写入单元格。

我有什么解决方案可以使用 VBA 将所需的公式写入单元格吗?

【问题讨论】:

  • 在我的初始帖子中更新了它,运行时错误1004。它通常是在公式有问题时生成的。例如 ActiveSheet.Cells(1,2).Formula = "=2+(3*4" 会产生同样的错误,因为缺少一个 final )。
  • 我看到 FormulaArray 可以使用 R1C1 样式的单元格命名,我明天试试。 (msdn.microsoft.com/en-us/library/office/ff837104.aspx)
  • 使用逗号。我知道您的系统使用分号列表分隔符,但 VBA 在将公式放入单元格时需要 EN-US 逗号。

标签: vba excel


【解决方案1】:

我敢打赌,因为它是一个数组公式,你应该使用 FormulaArray 属性。

ActiveSheet.Cells(Row + 3, Column + i).FormulaArray = 

【讨论】:

  • 仅供参考,来自here 的评论; If you use this property to enter an array formula, the formula must use the R1C1 reference style, not the A1 reference style (see the second example).
【解决方案2】:

Jeeped 对我的问题给出了正确答案,将分号列表分隔符替换为 EN-US 逗号。下面实际上没有问题:

ActiveSheet.Cells(Row + 3, Column + i).Formula = "=SUMPRODUCT(--(OFFSET(endResourceNaam,2,0):OFFSET(endResourceNaam,1000,0)=$A" & Row + 1 & "),--(OFFSET(endResourceNaam,2,4):OFFSET(endResourceNaam,1000,4)=$E" & Row + 1 & "),OFFSET(endResourceWeek,2," & ColumnLetter(Column - 1) & "$1):OFFSET(endResourceWeek,1000," & ColumnLetter(Column - 1) & "$1))"

我没有尝试过 FormulaArray 方法,因为这已经解决了我的问题。

【讨论】:

    猜你喜欢
    • 2018-04-29
    • 2010-11-08
    • 1970-01-01
    • 1970-01-01
    • 2022-11-22
    • 1970-01-01
    • 2017-06-29
    • 1970-01-01
    • 2022-01-14
    相关资源
    最近更新 更多