Google sheets - programmatically change cell background

Viewed 36

I know that I can use conditional formatting to set a cell background based on the content of another cell. But, is there a way to directly set a cell background via another cell's content, eg using an rgb value?

Something like this:

Cell 1A = "255,0,0"
Cell 2A background is red.
Change Cell 1A to "0,255,0"
Cell 2A background changes to green.

?

1 Answers

I was able to set the cell background value using setBackground:

function onEdit() {
  var ss = SpreadsheetApp.getActive();
  var sheet = ss.getSheets()[1];
  var cell = sheet.getRange("A1").getValue();
  var cell2 = sheet.getRange("B1");
  cell2.setBackground(cell);
}

This is how the value was set in the Sheet:

enter image description here

If you want to use setBackgroundRGB then you can use this code instead:

function ondEdit() {
  var ss = SpreadsheetApp.getActive();
  var sheet = ss.getSheets()[1];
  var cell = sheet.getRange("A1").getValue();
  Logger.log(cell)

  let cellinput = cell.split(',')
  
  
  const cellinput2 = cellinput.map((ele)=> (Number(ele)))
  var cell2 = sheet.getRange("B2");

  cell2.setBackgroundRGB(...cellinput2);
}

And this will be the output:

enter image description here

Related