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

两盒软妹~` 提交于 2019-11-27 22:15:12
Rubén

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

I had the same problem and tried to use the formula that Rubén created, but had a limitation. I couldn't use these formula inside of another one (I was trying to make a mid()). So made a different approach that worked:

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

EDIT: This answer is for the use case in the problem description, with the requirement of doing so with only native functions (no scripting).

Based on comments from AdamL to the question, the answer is that you cannot get the formula from a cell (instead of the value).

However, for the actual use case I was trying to solve, =ROW(A42) can be used to get a reference to a specific row that will update automatically with changes to rows.

bob

Use this:function =FORMULATEXT("cell")

Try using =formula(2,3) where the coordinates are (row #, col #)

Google sheet example at: https://docs.google.com/spreadsheets/d/1A1l0qdnNSHlJB-5DARGKDeIsbuCCLGuoYWm8sR29UTA/edit?usp=sharing

Showing the formulas...

And here's how it renders...

Note: Sometimes it takes a moment to load the formula, during which time you'll get some sort of error saying "Data loading..." or something.

Also note: I have no idea why this works, since formula is not a listed function for google sheets, but I have been using it in a spreadsheet of mine. Maybe the idea to try this came from Excel or something, I don't recall.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!