setBold() not working in google script

2019-08-24 15:25发布

问题:

I'm trying to bold a cell using google apps script, but unfortunately without any success.

Here is my code (replace "some code" by a suitable ID):

function myFunction() {
  var ss = SpreadsheetApp.openById("some code");
  var FontNumber = 20
  var targetCell = ss.setActiveSelection("A1").setFontSize(20).setBold();

}

And this is the error I get:

'TypeError: Cannot find function setBold in object Range. (line 7, file "Code")'

If I remove setBold() everything works fine. The function also does not appear in the autofill dropdown, but exists in the official documentation. What am I doing wrong?

回答1:

The documented setBold() function you are linking is part of the Document service for working with documents, rather than the SpreadsheetApp service for dealing with spreadsheets.

To set the font to bold on a spreadsheet Range object, use the setFontWeight() function.

function myFunction() {
  var ss = SpreadsheetApp.openById("some code");
  var FontNumber = 20
  var targetCell = ss.setActiveSelection("A1").setFontSize(20).setFontWeight("bold");

}

See the documentation for the Range class within the SpreadsheetApp service here:

https://developers.google.com/apps-script/reference/spreadsheet/range