脚本:如何将条件格式规则复制并重新应用到编辑范围?

Script: How to copy and reapply conditional formatting rules to a range on edit?

在 Google 表格中,当您粘贴新值时,应用条件格式的单元格范围可能会发生变化。我正在寻找一个脚本,它将复制 sheet 中存在的条件格式,并在人们粘贴数据时将其重新应用于新单元格。

我实际上并没有编写太多脚本,但我窃取了其他人的脚本并将它们放在一起科学怪人,直到它们模糊地起作用为止。这是我到目前为止偷的东西:

function onEdit(e) {
  var range = e.range;
  var sheet = range.getSheet();
  range.clearFormat();
  //clears formatting just on data that is pasted into the sheet

  var rules = sheet.getConditionalFormatRules();
  var newRules = [];
  for(var r = 0; r < rules.length; r++) {
    var booleanCondition = rules[r].getBooleanCondition();
    if(booleanCondition != null) {
      var rule = SpreadsheetApp.newConditionalFormatRule()
      .withCriteria(booleanCondition.getCriteriaType(), booleanCondition.getCriteriaValues())
      .setBackground(booleanCondition.getBackground())
      .setRanges([sheet.getRange("A:A"),sheet.getRange("C:C")])
      .build();
      newRules.push(rule);
      sheet.setConditionalFormatRules(newRules);
    }
  }
}

当然,问题是我正在获取 sheet 的所有条件格式规则并将它们全部应用到两列(A:A 和 C:C)。无论过去应用到哪些列,这些规则都会应用。

有人可以建议一种方法来复制预先存在的条件格式规则并将它们重新应用到我从中复制它们的列吗?

setRanges() 函数 [1] 是您需要设置要应用格式的范围的地方。在这种情况下,我使用了您从 onEdit 触发器 [2] 的事件对象中获取的编辑范围:

function onEdit(e) {
  var range = e.range;
  var column = range.getColumn();
  var sheet = range.getSheet();
  range.clearFormat();
  //clears formatting just on data that is pasted into the sheet

  //Get all Sheet rules and iterate through them
  var rules = sheet.getConditionalFormatRules();
  var newRules = [];
  newRules = newRules.concat(rules);

  for(var r = 0; r < rules.length; r++) {
    var rule = rules[r];
    //Get condition for each rule
    var booleanCondition = rule.getBooleanCondition();

    //Get the ranges to which each rule applies and iterate through
    var ranges = rule.getRanges();
    for (var i = 0; i < ranges.length; i++) {
      var ruleColumn = ranges[i].getColumn();  

      //If condition isn't null and edited column is the same as the one in the range, add rule
      if((ruleColumn == column) && (booleanCondition != null)) {
        var newRule = SpreadsheetApp.newConditionalFormatRule()
        .withCriteria(booleanCondition.getCriteriaType(), booleanCondition.getCriteriaValues())
        .setBackground(booleanCondition.getBackground())
        .setRanges([range])
        .build();
        newRules.push(newRule);
      }
    }
  }
  sheet.setConditionalFormatRules(newRules);
}

我还将这一行放在 for 循环之外,因为只需要在 sheet 中插入所有格式规则一次:

sheet.setConditionalFormatRules(newRules);

[1] https://developers.google.com/apps-script/reference/spreadsheet/conditional-format-rule-builder#setRanges(Range)

[2] https://developers.google.com/apps-script/guides/triggers/events