Google App Script: Find & Replace for specific columns

From teach me a better way to solve this problem, in your situation, I thought that when TextFinder is used, the process cost might be able to be reduced. When TextFinder is used for achieving your goal, it becomes as follows.

Sample script:

function myFunction() {
  var to_replace = "TextToFind";
  var replace_with = ""; //Leave blank to delete Text, or enter text in quotes to add string.

  var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('Sheet1');
  var lastRow = sheet.getLastRow();
  var ranges = ['B2:B' + lastRow, 'D2:D' + lastRow];
  sheet.getRangeList(ranges).getRanges().forEach(r => 
    r.createTextFinder(to_replace).matchEntireCell(true).replaceAllWith(replace_with)
  );
}

Note:

  • If you want to replace the part of cell value, please modify r.createTextFinder(to_replace).matchEntireCell(true).replaceAllWith(replace_with) to r.createTextFinder(to_replace).replaceAllWith(replace_with).

  • As an additional modification, if your script is modified, how about the following modification?

      function findAndReplace() {
        var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('Sheet1');
        var lastRow = sheet.getLastRow()
        var range = sheet.getRange('B2:D' + lastRow);
        var data = range.getValues();
        var to_replace = "TextToFind";
        var replace_with = ""; //Leave blank to delete Text, or enter text in quotes to add string.
        for (var r = 0; r < data.length; r++) {
          for (var i = 0; i < data[r].length; i++) {
            var value = data[r][i].toString();
            if (i != 1 && value.includes(to_replace)) {
              data[r][i] = data[r][i].replace(to_replace, replace_with);
            }
          }
        }
        range.setValues(data);
      }
    

References:

  • createTextFinder(findText)
  • Class TextFinder