【问题标题】:IF conditional formula in VBA - Run-time error '1004' [duplicate]VBA中的IF条件公式-运行时错误'1004'[重复]
【发布时间】:2021-11-10 11:40:54
【问题描述】:

我在 IF 语句的行收到运行时错误“1004”。查了之前的帖子,没找到相关的解决办法。 我的代码是

Sub RefreshFormulae()
Set sh = ActiveSheet
lastR = sh.Range("B" & sh.Rows.Count).End(xlUp).Row
sh.Range("$J$3:$K$" & lastR).ClearContents
sh.Range("$H$3:$H$" & lastR).Formula = "=$G3"
sh.Range("$K$3:$K$" & lastR).Formula = "=IF($I3<>""Not Found"";$I3;"""")"
End Sub

错误在下面的行中。我在这里有什么遗漏吗?

sh.Range("$K$3:$K$" &amp; lastR).Formula = "=IF($I3&lt;&gt;""Not Found"";$I3;"""")"

【问题讨论】:

  • 已经在 SO 上被问过很多次了,但是太累了,无法找到最合适的副本。在VBA中,您需要以英文格式指定您的公式,将";"替换为","
  • @FunThomas - 帮你搞定了。

标签: vba


【解决方案1】:

您需要在 VBA 中使用逗号 (,) 而不是分号 (;),因为函数内分隔符的区域格式仅适用于 Excel 公式栏界面,不适用于宏/VBA。

尝试: "=IF($I3&lt;&gt;" &amp; Chr(34) &amp; "Not Found"",$I3,"""")"

这将使整个块更改为:

Sub RefreshFormulae()
Set sh = ActiveSheet
lastR = sh.Range("B" & sh.Rows.Count).End(xlUp).Row
sh.Range("$J$3:$K$" & lastR).ClearContents
sh.Range("$H$3:$H$" & lastR).Formula = "=$G3"
sh.Range("$K$3:$K$" & lastR).Formula = "=IF($I3<>" & Chr(34) & "Not Found"",$I3,"""")"
End Sub

【讨论】:

  • 不知道为什么这个答案被赞成。 OP 的问题是 not 引号,它们是正确的。问题是您需要使用逗号,而不是分号
  • 相应更新,感谢@FunThomas
  • 是的,替换 ; ,解决了问题。谢谢
  • 您的第一句话具有误导性。 ; 适用于 Local 版本:.FormulaLocal.Formula2Local 等。
【解决方案2】:

在 VBA 中输入公式时需要使用逗号,即使在工作表中直接使用分号也是如此。

Sub RefreshFormulae()
Set sh = ActiveSheet
lastR = sh.Range("B" & sh.Rows.Count).End(xlUp).Row
sh.Range("$J$3:$K$" & lastR).ClearContents
sh.Range("$H$3:$H$" & lastR).Formula = "=$G3"
sh.Range("$K$3:$K$" & lastR).Formula = "=IF($I3<>""Not Found"",$I3,"""")"
End Sub

【讨论】:

  • 谢谢!正如这里指出的那样;正在制造问题
  • 只有在使用.Formula时才需要使用逗号。您的第一句话具有误导性,因为 .FormulaLocal; 是完全可能的。
猜你喜欢
  • 2016-10-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-10-22
  • 1970-01-01
  • 2016-10-26
  • 1970-01-01
  • 2016-03-25
相关资源
最近更新 更多