Search code examples
google-apps-scriptgoogle-sheetsgoogle-sheets-formulags-conditional-formatting

Randomly assign cell background color based on unique cell texts


I'm looking for some conditional formatting solution where a new cell background color is set to a unique cell text. The image below shows this.

enter image description here

The tricky part is that I won't know any of the values within the list beforehand.


Solution

  • How to assign a cell a unique color onEdit

    • Apps Script onEdit trigger run your function automatically each time a (manual!) edit was performed in your script
    • You onEdit function should compare your new entry (the last row of a predefined column) against the already existing values in the column with indexOf()
    • If the value already exists - use getBackground() to retrieve the background color of the corresponding cell and assign it to the new cell with setBackground(color)
    • If the value does not exist yet:
    • If the value already exists - it will be automatically assigned the correct background color by the already present rules.

    Sample:

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