setBackGroundRGB not accepting string

2019-08-29 02:34发布

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?

4条回答
Summer. ? 凉城
2楼-- · 2019-08-29 02:57

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;
查看更多
迷人小祖宗
3楼-- · 2019-08-29 03:05

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...

查看更多
放我归山
4楼-- · 2019-08-29 03:09

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);
}
查看更多
淡お忘
5楼-- · 2019-08-29 03:10

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);
}
查看更多
登录 后发表回答