在 Google 表格中刷新之前,用于添加条件格式的 AppS 脚本功能不起作用

AppScript function to add Conditional Formatting doesn't work until Refresh in Google Sheets

如标题所述,我有一些通过应用脚本设置的条件格式。我的问题是,在我进入 UI 并手动刷新它(例如,更改颜色,或删除并 re-adding 返回规则定义中的字符)之前,突出显示不起作用。我还尝试添加一条总括规则以将所有内容变为黑色,并且......所有内容都变为黑色,其中符合我的规则的值不会突出显示,直到我像上面在 UI.[=12 中所说的那样乱七八糟=]

这是我的代码:

function highlightExistingFarms(sheet){
  var rules = []; 
  var range = sheet.getRange("G:G")
  strRule = "=VLOOKUP(G:G,INDIRECT(\"'1862'!B:B\"),1,FALSE)";
  sheet.clearConditionalFormatRules();
  var rule = SpreadsheetApp.newConditionalFormatRule()
    .whenTextContains(strRule)
    .setBackground("#b3cfb0")
    .setRanges([range])
    .build();

    
  var ruleForceRefresh = SpreadsheetApp.newConditionalFormatRule()
    .whenCellNotEmpty()
    .setBackground("#000000")
    .setRanges([range])
    .build();
  var rules = sheet.getConditionalFormatRules();
  rules.push(rule);
  //rules.push(ruleForceRefresh);
  sheet.setConditionalFormatRules(rules);
  rules = sheet.getConditionalFormatRules();
  
  sheet.setConditionalFormatRules(rules);
  
    SpreadsheetApp.flush();
}

将应用条件格式规则,直到电子表格重新计算条件格式范围,另一方面,当使用条件格式规则的自定义公式时,而不是 whenTextContains 使用 whenFormulaSatisfied.

试试这个:

function highlightExistingFarms(sheet){
  var rules = []; 
  var range = sheet.getRange("G:G")
  strRule = "=VLOOKUP(G:G,INDIRECT(\"'1862'!B:B\"),1,FALSE)";
  sheet.clearConditionalFormatRules();
  var rule = SpreadsheetApp.newConditionalFormatRule()
    .whenFormulaSatisfied(strRule)
    .setBackground("#b3cfb0")
    .setRanges([range])
    .build();

  rules.push(rule);  
  
  sheet.setConditionalFormatRules(rules);
  
  /** Force a recalculation */
  const g1 = sheet.getRange('G1');
  const g1Value = g1.getValue();
  g1.clearContent();

  SpreadsheetApp.flush();
  
  g1.setValue(g1Value);
  
}