0
votes

I've got a sheet with multiple formulas (many many many) referencing another sheet. Since "replace all" doesn't work in formulas, I've tried to make a simple script to do it, but it outputs "unknown range name" at the end.

I've tried adding simple quotes, using setValue with "=" and setFormula without success.

Here's the code:

function changeFormula() {
  var strToFind = "DB!";
  var strToReplace = "'DB2'!";
  var range = SpreadsheetApp.getActiveSheet().getActiveRange();
  var numRows = range.getNumRows();
  var numCols = range.getNumColumns();
  for (var i = 1; i <= numRows; i++) {
    for (var j = 1; j <= numCols; j++) {
       cell = range.getCell(i,j);
       var currentFormula = cell.getFormula();

       if (currentFormula.indexOf(strToFind) > 0 )
       {
         var newFormula = currentFormula.replace(strToFind,strToReplace); //currentFormula + " string";
         cell.setValue("\'" + newFormula + "\'");
         cell.setValue("="+ cell.getValue().substring(1,cell.getValue().length-1))
         //cell.setValue(newFormula);
       }
    }
  }
}
2
Tried this script also, without success: productforums.google.com/forum/#!topic/docs/yPnrYiXDVOUbb_pt

2 Answers

0
votes

You will certainly need setFormula(). This seemed to work for me (I restructured a bit to get and set the formulae as a batch, which should give better performance):

function changeFormula()
{
  var strToFind = "DB!";
  var strToReplace = "'DB2'!";
  var range = SpreadsheetApp.getActiveSheet().getActiveRange();
  var formulae = range.getFormulas();
  for (var i = 0; i < formulae.length; i++) 
  {
    for (var j = 0; j < formulae[0].length; j++)
    {
       if (formulae[i][j].indexOf(strToFind) > -1)
       {
         formulae[i][j] = formulae[i][j].replace(strToFind, strToReplace);
       }
    }
  }
  range.setFormulas(formulae);
}
0
votes

This is what you can do to keep the values of all your formulas and remove the formulas. That way you can use the sheet away from the tabs it references.

  1. Duplicate Tab (so you don't blow out original with formulas in case you still need it in that format)
  2. Select all Cells on duplicate Tab and copy
  3. with all cells still selected Paste special values only from edit pulldown

The values stay and the formulas go away. Then you can copy to other workbooks etc. I know it is pretty simple

Not sure if that is what you need but it is what I needed and I figured I would share for you or anyone else that might wander by like I did.

Good luck

Bruce