在 VBA 中的公式中使用字符串变量

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/22176248/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-12 02:11:39  来源:igfitidea点击:

Using string variables within a formula in VBA

vbaexcel-vbaformulaexcel

提问by 7raiden7

I do not understand why this code doesn't work:

我不明白为什么这段代码不起作用:

Cells(i, formula_col_index).Value = "=IF(" & time_location & "<>" & time_benchmark & ",""ERROR"",""OK"")"

where

在哪里

time_location=" 17:00:00",
time_benchmark=" 17:30:00"

It keeps throwing application-defined (or object-defined) error.

它不断抛出应用程序定义(或对象定义)错误。

Thanks in advance.

提前致谢。

回答by Dmitry Pavliv

Since your variables time_locationand time_benchmarkcontains string values, you should include them in double quotes when using formula:

由于您的变量time_locationtime_benchmark包含字符串值,您应该在使用公式时将它们包含在双引号中:

Cells(i, formula_col_index).Value = "=IF(""" & time_location & """<>""" & time_benchmark & """,""ERROR"",""OK"")"