【问题标题】:Parse error from using .setValue or .SetFormula to set a formula containing a query function that has multiple single and double quotes使用 .setValue 或 .SetFormula 设置包含具有多个单引号和双引号的查询函数的公式时解析错误
【发布时间】:2014-10-04 16:16:37
【问题描述】:

我在工作表 A 中有一个公式,使用新的谷歌工作表可以正常工作;它包含一个查询函数,该函数根据工作表 B('Settings') 中的值和工作表 C('Data') 中的数据过滤日期。 工作公式:

=QUERY(Data!A1:G,"select G, sum(E) where F is not null AND toDate(D)>= date '" & text('Settings'!B5, "yyyy-MM-dd")&"' and toDate(D)<= date '" & text('Settings'!B6, "yyyy-MM-dd")&"'group by G pivot B label G'Pivot table for data in range'")

问题是我想使用 .setFormula.setValue 范围方法的脚本设置此公式,但公式字符串有问题。

这些方法将采用单引号或双引号包裹公式/值。因此,如果您使用单引号将公式括起来,则可以避免公式中的大多数双引号问题。 此外,您可以构建查询字符串,例如

formula = 'part of formula'+'another part of formula'; 
range.setFormula(formula);

尝试的解决方案是将我的公式用单引号和 每当遇到恰好在工作公式中的意外单引号时,我都会在此之前插入带有 + 号的有意单引号,就像括号中的内容 ('+)。 跟我到现在?我希望我很清楚。 所以尝试的改变看起来像这样。 首先,工作表中的公式:

=QUERY(Data!A1:G,"select G, sum(E) where F is not null AND toDate(D)>= date '" & text('Settings'!B5, "yyyy-MM-dd")&"' and toDate(D)<= date '" & text('Settings'!B6, "yyyy-MM-dd")&"'group by G pivot B label G'Pivot table for data in range'")

现在,尝试在脚本中设置:

range.setFormula('=QUERY(Data!A1:G,"select G, sum(E) where F is not null AND toDate(D)>= date '+'" & text('+'Settings'+'!B5, "yyyy-MM-dd")&"'+' and toDate(D)<= date '+'" & text('+'Settings'+'!B6, "yyyy-MM-dd")&"'+'group by G pivot B label G'+'Pivot table for data in range'+'")');

结果: 公式已写入,工作表显示错误:公式解析错误。我确信必须有一种方法来指示我何时需要将单引号作为字符串的一部分,而不是将我的一些单引号视为下一个字符串开始的标记(如果这有意义的话)。 感谢您的帮助,我会在弄清楚时发布。

【问题讨论】:

    标签: google-apps-script google-sheets formulas


    【解决方案1】:

    太简单了!而不是 '+ 只是使用 \ 来转义我的公式中的单引号,所以答案是: range.setFormula('=QUERY(Data!A1:G,"select G, sum(E) where F is not null AND toDate(D )>= date \'" & text(\'Settings\'!B5, "yyyy-MM-dd")&"\' and toDate(D)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-12-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-17
      • 2018-09-02
      • 2016-04-15
      • 2021-12-12
      相关资源
      最近更新 更多