setBackground() or setFontColor not working in GAS

2019-08-01 18:10发布

I was having trouble getting my script to highlight a range and after debugging for a bit, realized that there seems to be something wrong with the call of type

range.setBackground("name of color");

So, I went to GAS reference website and used the example from their page: https://developers.google.com/apps-script/reference/spreadsheet/range#setFontColor(String)

var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheets()[0];
var cell = sheet.getRange("B2");
cell.setFontColor("red");

This code results in !ERROR. If I force a return before setFontColor() call, all is fine. (and by fine I mean it returns from the function without an error, but of course, without having set the color).

What am I doing wrong?

2条回答
可以哭但决不认输i
2楼-- · 2019-08-01 18:21

You havent put enough info, but i assume you are calling your function from a cell formula as a custom function. See the docs, used like that you cant change a cell other than the current cell.

查看更多
混吃等死
3楼-- · 2019-08-01 18:30

I can't reproduce the error. The following code work as expected:

/* CODE FOR DEMONSTRATION PURPOSES */
function setFontAndBackgroundColorCell() {
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var sheet = ss.getSheets()[0];
  var cell = sheet.getRange('B2');
  cell.setFontColor('yellow');
  cell.setBackground('red');
  cell.setValue('TEST');
}
/* CODE FOR DEMONSTRATION PURPOSES */

enter image description here

查看更多
登录 后发表回答