Search code examples
google-apps-scriptgoogle-sheetsgoogle-sheets-macros

How to write a find and replace script in Sheets


I am trying to write a script that takes a text version of a formula starting with "@" and replaces it with "=" so that the formula actually works. I have tried to use replace and substitute formulas but after running those formulas, the original formulas don't pull.

Here is a link to the spreadsheet:

https://docs.google.com/spreadsheets/d/1OTVzynWNsi7NJ6-3gFonrrWhy2lKq_ibe6KG-p5Yibk/edit#gid=725037056

Here is what my current script looks like:

var sheet = spreadsheet.getActiveSheet();
  sheet.getRange(1, 1, sheet.getMaxRows(), sheet.getMaxColumns()).activate();
  spreadsheet.getActiveRangeList().clear({contentsOnly: true, skipFilteredRows: true});
  spreadsheet.getRange('A1').activate();
  spreadsheet.getRange('Formulas!A16:M17').copyTo(spreadsheet.getActiveRange(), SpreadsheetApp.CopyPasteType.PASTE_VALUES, false);
  spreadsheet.getRange('A2').activate();
  currentCell = spreadsheet.getCurrentCell();
  spreadsheet.getSelection().getNextDataRange(SpreadsheetApp.Direction.NEXT).activate();
  currentCell.activateAsCurrentCell();

  //This is where the find replace formula needs to go
  currentCell.toString().replace("@", "=");

Solution

  • Try it this way:

    function copyFormulas() {
      var ss=SpreadsheetApp.getActive();
      var ssh=ss.getSheetByName('Formulas');
      var srg=ssh.getRange('A16:M17');
      var vA=srg.getValues();
      for(var i=0;i<vA[1].length;i++) {
        vA[1][i]=vA[1][i].toString().replace('@','=');    
      }
      var dsh=ss.getSheetByName('Script');
      dsh.getRange(1,1,1,srg.getWidth()).setValues([vA[0]]);
      dsh.getRange(2,1,1,srg.getWidth()).setFormulas([vA[1]]);
    }