How do you get the formula from a cell instead of the value?

前端 未结 5 2225
执笔经年
执笔经年 2020-12-05 14:55

How do you get the literal value (the formula) from a cell instead of the result value?

EXAMPLE DESIRED:

  • A2: \"Foo\"
  • B3: \"=A2\" - so it
5条回答
  •  生来不讨喜
    2020-12-05 15:53

    Use getFormula() or getFormulaR1C1() methods to get the formula of a cell.

    Example adaptated from https://webapps.stackexchange.com/a/92156/88163

    The following custom function will return the formula of the referenced cell but if the reference is not valid, it will return an error message.

    function CELLFORMULA(reference) {
      var ss = SpreadsheetApp;
      var sheet = ss.getActiveSheet();
      var formula = ss.getActiveRange().getFormula();
      var args = formula.match(/=\w+\((.*)\)/i);
      try {
        var range = sheet.getRange(args[1]);
      }
      catch(e) {
        throw new Error(args[1] + ' is not a valid range');
      }
      return range.getFormula();
    }
    

    Example of use of the above custom function

    A2: FOO
    B3: Formula =A2, value FOO
    C3: Formula =CELLFORMULA(B3), value =A2

提交回复
热议问题