缺少数量时无法引用单元格的Google Apps脚本条件格式

时间:2019-09-13 17:23:06

标签: google-apps-script conditional-formatting

我正在构建一个电子表格,以根据每个类别的预算值来跟踪每月的费用。如果值小于或等于预算金额,我想突出显示一个单元格,如果大于或等于预算金额,我要突出显示红色。

如果我输入金额的数值,我就可以使用它,但是预算有时会逐月变化,所以我希望能够启动一个新的月份电子表格,并有条件地设置基于单元格颜色的格式参考预算单元。我可以在excel VBA中执行此操作,但是无法将引用传递给whenNumberLessThan函数。

//This errors out on trying to concatenate the row onto what is in the D column
var ruleRed = SpreadsheetApp.newConditionalFormatRuleBuilder()
.whenNumberLessThan("=D".concat(row))
.setBackground("#FF0000")
.setRanges([month.getRange("C".concat(row))])
.build();

//This works with 1200 or any other numeric value
var ruleRed = SpreadsheetApp.newConditionalFormatRuleBuilder()
.whenNumberLessThan(1200)
.setBackground("#FF0000")
.setRanges([month.getRange("C".concat(row))])
.build();

2 个答案:

答案 0 :(得分:2)

从我的角度来看,仅使用表格即可简化计划的工作,因为可以通过自定义公式使用条件格式设置(请参见文档here)。 但是,如果您确实需要使用Google脚本,则有2种可能的选择:

1。在脚本上获取预算单元格值,然后使用.whenNumberLessThan

您应该获取单元格值,然后使用.whenNumberLessThan,因为如上所述,该函数仅接受数字。代码看起来像这样:

var budgetValue = SpreadsheetApp.getRange("D".concat(row)).getValue();
var ruleRed = SpreadsheetApp.newConditionalFormatRuleBuilder()
.whenNumberLessThan(budgetValue)
.setBackground("#FF0000")
.setRanges([month.getRange("C".concat(row))])
.build();

2。使用.whenFormulaSatisfied

这应该使用与我提到的带自定义公式的条件相同的概念

var ruleRed = SpreadsheetApp.newConditionalFormatRuleBuilder()
.whenFormulaSatisfied("=C1<$D$".concat(row))
.setBackground("#FF0000")
.setRanges([month.getRange("C".concat(row))])
.build();

答案 1 :(得分:0)

谢谢乔纳斯!这很棒!我应该考虑这样做。这是我最终使用的内容,因此我可以在C列和D列上同时指定行

var ruleRed = SpreadsheetApp.newConditionalFormatRule()
.whenFormulaSatisfied("=C".concat(row)+"<$D$".concat(row))
.setBackground("#FF0000")
.setRanges([month.getRange("C".concat(row))])
.build();
相关问题