Google Sheets – How to Use Google Script Replace Function

google sheetsgoogle-apps-script

Is it possible to build a Google Script where I can select a cell, take its function, replace the cell references (instead of C2,C3,C4, etc. make it AC1,AC2,AC3, etc.), and then return the output of the new function?

If so, how would one go about writing that script?

Best Answer

Like this:

  1. Get the selected cell (for simplicity, I deal only with one cell even if a larger range is selected)
  2. Get the formula from it.
  3. If there is a formula, replace all references to C(number) with AC(number).
  4. Put the new formula into the cell.

function replaceReferences() {
  var cell = SpreadsheetApp.getActiveSheet().getActiveRange().getCell(1,1);
  var formula = cell.getFormula();
  if (formula) {
    var newFormula = formula.replace(/(C\delta+)/g, "A$1");
    cell.setFormula(newFormula);
  }
}