我需要帮助来编写将评估公式的函数的脚本。
示例:
Cell A1 = 1
Cell B1 = 2
Cell C1 = A1 + B1, which displays the sum of two numbers = 3
Cell D1 `= 1 + 2, which displays above formula with entered values
我该怎么做?
更新
我发现只有脚本采用公式并按原样显示,而没有在公式参数中输入值,即`= A1 + B1
function GETFORMULA(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();
}
答案 0 :(得分:1)
我做到了!公式评估脚本已准备就绪:
function eval(reference) {
var ss = SpreadsheetApp;
var sheet = ss.getActiveSheet();
var commandFormula = ss.getActiveRange().getFormula();
var commandFormulaArgs = commandFormula.match(/=\w+\((.*)\)/i);
try {
var commandFormulaRange = sheet.getRange(commandFormulaArgs[1]);
}
catch(e) {
throw new Error(args[1] + ' is not a valid range');
}
var calcFormula = commandFormulaRange.getFormula();
var calcFormulaArgs = calcFormula.match(/(\w+)/gi);
for(var i in calcFormulaArgs){
try {
calcFormula = calcFormula.replace(calcFormulaArgs[i], " " + sheet.getRange(calcFormulaArgs[i]).getValue() + " ");
}
catch(e) {
throw new Error(args[1] + ' is not a valid range');
}
}
return calcFormula;
}
脚本替换实际单元格值上的所有单元格引用。