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

在Google表格中,粘贴新值时,条件格式应用于的单元格范围可以更改。我正在寻找一个脚本,该脚本将复制工作表中存在的条件格式,并在人们粘贴数据时将其重新应用于新单元格。

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

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);
    }
  }
}

当然,问题在于我正在获取该工作表的所有条件格式设置规则,并将其全部应用于两列(A:A和C:C)。不管它们曾经应用于什么列,都将应用这些规则。

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

inlovelove 回答:脚本:如何在编辑时将条件格式设置规则复制并重新应用于范围?

需要在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.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

本文链接:https://www.f2er.com/3118929.html

大家都在问