2

我正在尝试在 Google 表格中将条件格式规则从我的一张表格复制到其他表格。我知道,我可以复制并使用“特殊粘贴”来复制/粘贴它们,但我特别想使用脚本,因为我已经设置了一个自动创建新工作表的脚本,我想应用对我制作的所有工作表进行条件格式设置,因为整个电子表格是一种日志,并且包含条件格式的特定列适用于整个工作表。这是我所拥有的:

截屏

4

2 回答 2

2

使用 SpreadsheetApp函数ConditionalFormatRuleBuilder类,您可以从工作表中的规则创建新规则并将它们插入到新工作表中。我创建了以下代码,该代码用于从“Merkler”表中获取所有规则并将它们插入到“新表”中,前提是这些规则应用于“F”列。

function copyFormat() {
  //Get the Spreadsheet where the Merkler and new sheet are in
  var spreadSheet = SpreadsheetApp.openById("[SPREADSHEET-ID]");
  //The source sheet with the formatting in column F is called Merkler
  var sheet = spreadSheet.getSheetByName("Merkler");
  //The target sheet is called "New Sheet"
  var newSheet = spreadSheet.getSheetByName("New sheet");
  
  //The formatting will be taken from column F and copy to it in new Sheet
  var range = newSheet.getRange("F2:F1000");
  var column = 6; //F is the 6th column

  //Get all Sheet rules and iterate through them
  var rules = sheet.getConditionalFormatRules();
  var newRules = [];
  
  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);
      }
    }
  }
  newSheet.setConditionalFormatRules(newRules);
}

您需要替换电子表格 ID。

于 2019-11-20T16:58:29.240 回答
1
    function passConditionalFormat(sourceSheetName, targetSheetName) {
      var ss = SpreadsheetApp.getActive();
      //The source of data formatting rules
      var sourceSheet = ss.getSheetByName(sourceSheetName);
      var range = sourceSheet.getRange(1, 1, sourceSheet.getMaxRows(), sourceSheet.getMaxColumns());
      //The target of data formatting rules
      var targetSheet = ss.getSheetByName(targetSheetName);
      
      range.copyFormatToRange(targetSheet, 1, sourceSheet.getMaxColumns(), 1, sourceSheet.getMaxRows());
    }

您可以使用以下选项之一:

  1. copyFormatToRange(sheet, column, columnEnd, row, rowEnd)
  2. copyFormatToRange(gridId, column, columnEnd, row, rowEnd)

请注意,此解决方案仅适用于将条件格式从一张工作表传递到同一电子表格中的另一张工作表。

于 2020-07-13T18:51:54.743 回答