Search code examples
google-apps-scriptscriptinggoogle-apps

Can't seem to get any Google Scripts code to work to BOLD all occurrences of one specific word


I found that RichTextValue should work, but I'm not sure where to put the word in on this code and when I use this code

function Bold() {
  for (var i = 4; i <=160; i++){
    var cell = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet().getRange(i, 1);
    cell.setRichTextValue(SpreadsheetApp.newRichTextValue()
        .setText(cell.getValue())
        .setTextStyle(2, 16, SpreadsheetApp
          .newTextStyle()
          .setBold(true)
          .build())
        .build());
  }
}

I get an illegal argument error and I have no idea where I am going wrong. I am not a developer but got pretty good at VBA. Unfortunately I'm really battling with Google Scripts. Any help would be appreciated as this was the only thing I could not get right. Thank you!


Solution

  • Let's consider the following code:

    function testBold() {
      var boldStyle = SpreadsheetApp.newTextStyle().setBold(true).build();
      var cells = SpreadsheetApp.getActive().getRange('Лист1!A1:A100');
    
      var values = cells.getValues();  // initial values
      var richValues = values.map(     // become rich values
        function(v) {
          var richBuilder = SpreadsheetApp.newRichTextValue().setText(v[0]);
          if (v[0].length && v[0].length > 16) richBuilder = richBuilder.setTextStyle(2, 16, boldStyle);
          return [richBuilder.build()];
        }
      );
    
      cells.setRichTextValues(richValues);
    }
    

    At first, we avoid to read data from each cell sequencially, because there is more powerful way to read range data at once.

    Further, we use the power of JS map() function to obtain desired rich styling for each input values array element. Do not remember to check input values to have string type and sufficient length before applying the style.

    At last we write rich-style data back to the same sheet range.