Convert a text string to a formula in a spreadsheet

别等时光非礼了梦想. 提交于 2021-01-29 04:54:09

问题


I'm trying to develop an interactive spreadsheet that creates a narrative for a budget document. There will be a variety of options. Once the user selects an item, it will help them calculate the total. I want to setup option boxes that they fill in. For example, four cells will be allowed for input B1:B4. I am going to name each of the four cells (i.e. A, B, C, D). In the reference document I want to write various formulas. In some cases I might need "(A+B)*C" in another I might need "A * B * C" or "(A+B+C)/D" ... The spreadsheet would lookup the text formula, and I want to then convert it. So in the case of the lookup finding "(A+B)*C" I want it to convert it to =(indirect(A)+indirect(B))*indirect(C) which would then get the values from A (which is B1), B (which is B2) and so on.

Essentially, I would like to use or create something that is exactly the opposite of Excel's FORMULATEXT() function. I would prefer to do this in Google Sheets but I am willing to use Excel if I need to. I have a very basic understanding of both Google's scripting and VBA, and am willing to create if necessary, but not even sure how to tackle it.

Suggestions?


回答1:


I found a way to do it in Google Apps Script:

function reCalc() { 
var sheet = SpreadsheetApp.getActiveSheet();  
var src = sheet.getRange("J26");   // The cell which holds the formula
var str = src.getValue(); 
str = str.replace('A', 'indirect("OPTA")').replace('B', 'indirect("OPTB")').replace('C', 'indirect("OPTC")').replace('D', 'indirect("OPTD")').replace('ENR', 'indirect("ENR")'); 
var cell = sheet.getRange("J30");  // The cell where I want the results to be
cell.setFormula(str);              // Setting the formula.
}

Thank you to SpiderPig for giving me the idea!



来源:https://stackoverflow.com/questions/35022815/convert-a-text-string-to-a-formula-in-a-spreadsheet

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