Home > Blockchain >  How would I modify a Google Script that applies conditional formatting to accept a list of cells rat
How would I modify a Google Script that applies conditional formatting to accept a list of cells rat

Time:03-31

I found this wonderful script here:enter image description here

CodePudding user response:

The argument of setRanges(ranges) of Class ConditionalFormatRuleBuilder is Range[]. So when you want to use "C2, C3, C4, H1, H2, H3, N5" as the ranges, as a sample modification, how about the following modification?

Modified script:

function applyConditionalFormat() {
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var sheet = ss.getActiveSheet();
  var rule = createRule(sheet, "C2, C3, C4, H1, H2, H3, N5", "=$B2>=10", "#cc0000");
  sheet.setConditionalFormatRules([rule]);
}

function createRule(sheet, rangeNotation, formula, color) {
  var ranges = sheet.getRangeList(rangeNotation.split(",").map(e => e.trim())).getRanges();
  var rule = SpreadsheetApp.newConditionalFormatRule()
    .whenFormulaSatisfied(formula)
    .setBackground(color)
    .setRanges(ranges)
    .build();
  return rule;
}
  • In this modification, the value of rangeNotation given by createRule(sheet, "C2, C3, C4, H1, H2, H3, N5", "=$B2>=10", "#cc0000") is converted to the value of Range[]. And, the value is used with setRanges(ranges).

References:

  • Related