根据独特的单元格文本随机分配单元格背景颜色

Randomly assign cell background color based on unique cell texts

我正在寻找一些条件格式解决方案,其中新的单元格背景颜色设置为唯一的单元格文本。下图显示了这一点。

棘手的部分是我事先不知道列表中的任何值。

如何为单元格指定唯一颜色onEdit

  • Apps 脚本 onEdit 每次在您的脚本中执行(手动!)编辑时都会自动触发 运行 您的函数
  • onEdit 函数应该将您的新条目(预定义列的最后一行)与具有 indexOf()
  • 的列中已经存在的值进行比较
  • 如果该值已经存在 - 使用 getBackground() to retrieve the background color of the corresponding cell and assign it to the new cell with setBackground(color)
  • 如果该值还不存在:
    • 使用函数 generate a random color
    • 检查 indexOf 此颜色是否包含在已经存在的背景颜色中
    • build a new conditional rule 为新文本分配新颜色
  • 如果该值已存在 - 将由已存在的规则自动为其分配正确的背景颜色。

样本:

function onEdit(e) {
  if(e.range.getColumn()==1){
    var text = e.value;
    var sheet = SpreadsheetApp.getActive().getActiveSheet();
    var range = sheet.getRange(1,1,sheet.getLastRow(),1);
    var values = range.getValues();
    var array = [];
    var row = e.range.getRow();
    for (var i =0; i <values.length; i++){
      if(row!=(i+1))
      {
        array.push(values[i][0]);
      }
    }
    if(array.indexOf(text)==-1){
      var backgrounds = range.getBackgrounds();
      var color = getRandomColor();
      while(backgrounds.indexOf(color)>-1){
        color = getRandomColor();
      }
      buildConditionalFormatting(text, color)
    }
  } 
}

function getRandomColor() {
  var letters = '0123456789abcdef';
  var color = '#';
  for (var i = 0; i < 6; i++) {
    color += letters[Math.floor(Math.random() * 16)];
  }
  return color;
}


function buildConditionalFormatting(text, color){
  var sheet = SpreadsheetApp.getActiveSheet();
  var formattingRange = sheet.getRange("A:A");
  var rule = SpreadsheetApp.newConditionalFormatRule()
  .whenTextEqualTo(text)
  .setBackground(color)
  .setRanges([formattingRange])
  .build();
  var rules = sheet.getConditionalFormatRules();
  rules.push(rule);
  sheet.setConditionalFormatRules(rules);

}