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

7ra*_*en7 1 excel vba formula excel-vba

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

Cells(i, formula_col_index).Value = "=IF(" & time_location & "<>" & time_benchmark & ",""ERROR"",""OK"")"
Run Code Online (Sandbox Code Playgroud)

哪里

time_location=" 17:00:00",
time_benchmark=" 17:30:00"
Run Code Online (Sandbox Code Playgroud)

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

提前致谢.

Dmi*_*liv 6

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

Cells(i, formula_col_index).Value = "=IF(""" & time_location & """<>""" & time_benchmark & """,""ERROR"",""OK"")"
Run Code Online (Sandbox Code Playgroud)