简体   繁体   中英

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

I'm trying to write a script which will take a column of hex codes and color the adjacent column's background color to be that hex code color, but I'm just not sure how to do it.

I've been looking at these:

1) https://developers.google.com/apps-script/reference/spreadsheet/range#setbackgroundcolor

2) https://developers.google.com/apps-script/reference/spreadsheet/range#getcellrow-column

3) Google Spreadsheet: Script to Change Row Color when a cell changes text;

But haven't really hade any progress. Any help would be appreciated!

Thanks!

Something like this should solve your problem:

function onEdit() {

  var sheet = SpreadsheetApp.getActiveSheet();
  var range = sheet.getDataRange();
  var actCell = sheet.getActiveCell();
  var actData = actCell.getValue();
  var actRow = actCell.getRow();
  if (actData != '' && actRow != 1)  //Leaving out empty and header rows
  {
    range.getCell(actRow, 2).setBackground(actData);
  }

}

Although, this only colors one cell at a time, but it portrays how you can set a background color based on cell input. Depending on your use case, whether you are copy-pasting multiple hex codes at a time or whether you have an existing list of hexcodes and you would like to show their color against those, using getCell(row,column).setBackground(String) should be able to help you out.

Here's a solution that will act only on specified columns and will also make sure the text entered is a valid hex color code. You could have it watch one column for changes and apply the background color changes to any other column, not just the immediately adjacent one. You also don't have to worry about cells containing other text, like headers, since this code will ignore them. And you can paste multiple lines into the spreadsheet, as this function will operate on any edited cells in the watched column.

It's worth noting that this code isn't foolproof, and I haven't optimized it. For example, you will probably get an error if you try to change the background color of a cell that is beyond the active sheet's current maximum range (you could easily write code to add new columns to the sheet if necessary). Also, if you paste an extremely large number of rows into the sheet, it's possible the function could time out. Though I doubt this would happen in normal use, the best practice would technically be to apply the changes all at once at the end of the forEach loop instead of one at a time.

You could rewrite this as a menu function, too, if that's what you meant by "take a column of hex codes." 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, AF, or af.

SpreadsheetApp.flush() may not be strictly necessary, but it's supposed to afford real time updating of changes in this sort of situation.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM