0

The class setBackgroundRGB() works if I pass it a literal

setBackgroundRGB(255,255,255); 

but if I pass it a variable instead, it fails:

_Color = "255, 255, 255";

setBackgroundRGB(_Color); 

Does not work and returns an error

`Cannot find method setBackgroundRGB(string)`

Do i need to do some kind of conversion here that I am not aware of?

Chris
  • 8,527
  • 10
  • 34
  • 51
VikingBlooded
  • 884
  • 1
  • 6
  • 17

5 Answers5

2

You need to pass an array. The following should work:

_Color = [255, 255, 255];
setBackgroundRGB(_Color); 

Note - this is essentially what the post above is doing -- split() converts strings to arrays...

0

You are passing a string. It takes integers.

Try This:

_Color = 255,255,255

I doubt that will work however. You may need to do multiple variables for each

red = 255;
green = 255;
blue = 255;
0

Indeed the API does not have a method setBackgroundRGB(string), provides a method setBackgroundRGB(Integer, Integer, Integer), however, an option to achieve what you need, having a string as input is:

function setColorToRange() {
  var colorRGB = '0, 255, 0';
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var sheet = ss.getActiveSheet();      
  var range = sheet.getRange('A1:B3');
  range.setBackgroundRGB.apply(range, colorRGB.split(', '));
}

UPDATE

To get the vector can be applied several improvements, widening a little the example presented, we integrate some of the improvements indicated in the comments, resulting in the following:

function setColorToRange() {
  var colorRGB = '0, 255, 0';
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var sheet = ss.getActiveSheet();      
  var range = sheet.getRange('A1:B3');
  var arrColorRGB = getRGB(RGBString);
  range.setBackgroundRGB.apply(range, arrColorRGB);
}

function getRGB(RGBString) {
  // Returns a vector of integers
  return RGBString.replace(/ /g, '').split(',').map(returnInt);
}

function returnInt(value) {
  return parseInt(value, 10);
}
wchiquito
  • 16,177
  • 2
  • 34
  • 45
0

Just another variant of the same approach using range and RGBstring as parameters :

function test(){ // to define 2 parameters
  var range = SpreadsheetApp.getActiveSheet().getRange('A1:B3');
  setColorToRange(range,'0, 255, 0');
}

function setColorToRange(range,RGBString) {
  var colorRGB = RGBString.replace(/ /g,'').split(',');// first remove spaces if present then split on comma only to get the array of integers
  range.setBackgroundRGB.apply(range, colorRGB);
}
Serge insas
  • 45,904
  • 7
  • 105
  • 131
0

const rgb = { red : 224, green : 224, blue : 224 }

....setBackgroundRGB(rgb.red, rgb.green, rgb.blue);

Virgil H.
  • 33
  • 1
  • 6
  • A 'good answer' also includes a sentence or two in plain text that explains why you think your solution will work. Please visit SO Help Center and specifically this guideline for more details >>> stackoverflow.com/help/how-to-answer – inputforcolor Dec 23 '21 at 13:35