Google Spreadsheet: Script to change background color of a cell based on a hex code in the neighboring cell - Stack Overflow

PHOTO EMBED

Wed Aug 14 2024 09:49:04 GMT+0000 (Coordinated Universal Time)

Saved by @baamn #javascript

// regex for hex color codes
HEX_COLOR_REGEX = /(^#[0-9A-Fa-f]{3}$)|(#[0-9A-Fa-f]{6}$)/;

// column to watch for changes (i.e. column where hex color codes are to be entered)
HEX_CODE_COLUMN = 1; // i.e. column A

// column to change when above column is edited
HEX_COLOR_COLUMN = 2; // i.e. column B

// utility function to test whether a given string qualifies as a hex color code
function hexTest(testCase) {
  return HEX_COLOR_REGEX.test(testCase);
}

function onEdit(e) {
  var range = e.range;
  var row = range.getRow();
  var column = range.getColumn();
  if (column === HEX_CODE_COLUMN) {
    var values = range.getValues();
    values.forEach( function checkCode(rowValue, index) {
      var code = rowValue[0];
      if (hexTest(code)) {
        var cell = SpreadsheetApp.getActiveSheet().getRange(row + index, HEX_COLOR_COLUMN);
        cell.setBackground(code);
        SpreadsheetApp.flush();
      }
    });
  }
}
content_copyCOPY

The code below only works on newly entered text. For pre-existing text, rename the function and modify it to check the desired column automatically instead of functioning as a trigger (or check the active range if you want to select only certain cells). No muss, no fuss. The regular expression assumes that a valid hex color code is a string that starts with an octothorpe and is followed by either 3 or 6 characters, each of which must be 0-9, A-F, or a-f. SpreadsheetApp.flush() may not be strictly necessary, but it's supposed to afford real time updating of changes in this sort of situation

https://stackoverflow.com/questions/30766943/google-spreadsheet-script-to-change-background-color-of-a-cell-based-on-a-hex-c?rq