How do you get the literal value (the formula) from a cell instead of the result value?
EXAMPLE DESIRED:
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.
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.
Use this:function =FORMULATEXT("cell")
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