Related
Use Case
Example. I have a named range Apples (address "Sheet10!B2:B"), which in use for data validation for plenty of sheet cells. The data range for Apples can be changed (in a script), e.g. to "Sheet10!D2:D".
It works from UI
I can set manually a named range as a data source of data validation.
In this case, the data validation of a cell will always refer to the named range Apples with updated the data range.
How to make it in Google Apps Script?
GAS Limits
The code, for setting data validation, should look like this, if you have a namedRange object:
mySheet.getRange('F5')
.setDataValidation(
SpreadsheetApp.newDataValidation()
.requireValueInRange(
namedRange.getRange()
)
.setAllowInvalid(false)
.build()
);
DataValidationBuilder.requireValueInRange() does not work here as it requires only class Range (it cannot get NamedRange), and no reference to a named range will be used.
Is there a workaround or so?
UPD1 - Spreadsheet.getRangeByName() does not work
Getting range by name does not help, the data validation will get actual range address.
SpreadsheetApp.getActive().getRangeByName("Apples")
UPD2 No way to make it so far in GAS
As #TheMaster posted, it's not possible at this moment.
Please set +1 for posts:
https://issuetracker.google.com/issues/143913035
https://issuetracker.google.com/issues/203557342
P.S. It looks like the only solution will work is Google Sheets API.
I thought that in your situation, I thought that when Sheets API is used, your goal might be able to be used.
Workaround 1:
This workaround uses Sheets API.
Usage:
1. Prepare a Google Spreadsheet.
Please create a new Google Spreadsheet.
From Example. I have a named range Apples (address "Sheet10!B2:B"), which in use for data validation for plenty of sheet cells. The data range for Apples can be changed (in a script), e.g. to "Sheet10!D2:D"., please insert a sheet of "Sheet10" and put sample values to the cells "B2:B" and "D2:D".
Please set the named range Sheet10!B2:B as Apple.
2. Sample script.
Please copy and paste the following script to the script editor of Spreadsheet and save the script. And, please enable Sheets API at Advanced Google services.
function myFunction() {
const namedRangeName = "Apple"; // Please set the name of the named range.
const ss = SpreadsheetApp.getActiveSpreadsheet();
const sheet = ss.getSheetByName("Sheet10");
const requests = [{ updateCells: { range: { sheetId: sheet.getSheetId(), startRowIndex: 0, endRowIndex: 1, startColumnIndex: 0, endColumnIndex: 1 }, rows: [{ values: [{ dataValidation: { condition: { values: [{ userEnteredValue: "=" + namedRangeName }], type: "ONE_OF_RANGE" }, showCustomUi: true } }] }], fields: "dataValidation" } }];
Sheets.Spreadsheets.batchUpdate({ requests }, ss.getId());
}
In this request, the name of the named range is directly put to userEnteredValue.
3. Testing.
When this script is run to the above sample Spreadsheet, the following result is obtained.
When this demonstration is seen, first, you can see the named range of "Apple" which has the cells "B1:B1000". When a script is run, data validation is put to the cell "A1" with the named range of "Apple". In this case, the values of data validation indicate "B1:B1000". When the range named range "Apple" is changed from "B1:B1000" to "D1:D1000" and the data validation of "A1" is confirmed, it is found that the values are changed from "B1:B1000" to "D1:D1000".
Workaround 2:
This workaround uses the Google Spreadsheet service (SpreadsheetApp). In the current stage, it seems that the Google Spreadsheet service (SpreadsheetApp) cannot directly achieve your goal. This has already been mentioned in the discussions in the comment and TheMaster's answer. When you want to achieve this, how about checking whether the range of the named range is changed using OnChange as following workaround 2?
Usage:
1. Prepare a Google Spreadsheet.
Please create a new Google Spreadsheet.
From Example. I have a named range Apples (address "Sheet10!B2:B"), which in use for data validation for plenty of sheet cells. The data range for Apples can be changed (in a script), e.g. to "Sheet10!D2:D"., please insert a sheet of "Sheet10" and put sample values to the cells "B2:B" and "D2:D".
Please set the named range Sheet10!B2:B as Apple.
2. Sample script.
Please copy and paste the following script to the script editor of Spreadsheet and save the script. And, please install OnChange trigger to the function onChange.
First, please run createDataValidation. By this, data validation is put to the cell "A1" of "Sheet10". In this case, the set range is the range retrieved from the named range "Apple". So, in this case, the range is Sheet10!B2:B1000.
As the next step, please change the range of the named range from Sheet10!B2:B1000 to Sheet10!D2:D1000. By this, onChange` function is automatically run by the installed OnChange trigger. By this, the data validation of "A2" is updated. By this, the values of data validation are changed.
const namedRangeName = "Apple"; // Please set the name of the named range.
const datavalidationCell = "Sheet10!A2"; // As a sample. data validation is put to this cell.
function onChange(e) {
if (e.changeType != "OTHER") return;
const range = e.source.getRangeByName(namedRangeName);
const a1Notation = `'${range.getSheet().getSheetName()}'!${range.getA1Notation()}`;
const prop = PropertiesService.getScriptProperties();
const previousRange = prop.getProperty("previousRange");
if (previousRange != a1Notation) {
const rule = SpreadsheetApp.newDataValidation().requireValueInRange(e.source.getRangeByName(namedRangeName)).setAllowInvalid(false).build();
e.source.getRange(datavalidationCell).setDataValidation(rule);
}
prop.setProperty("previousRange", a1Notation);
}
// First, please run this function.
function createDataValidation() {
const ss = SpreadsheetApp.getActiveSpreadsheet();
const rule = SpreadsheetApp.newDataValidation().requireValueInRange(ss.getRangeByName(namedRangeName)).setAllowInvalid(false).build();
ss.getRange(datavalidationCell).setDataValidation(rule);
const prop = PropertiesService.getScriptProperties();
const range = ss.getRangeByName(namedRangeName);
const a1Notation = `'${range.getSheet().getSheetName()}'!${range.getA1Notation()}`;
prop.setProperty("previousRange", a1Notation);
}
References:
Method: spreadsheets.batchUpdate
UpdateCellsRequest
DataValidationRule
Currently, This seems to be impossible. This is however a known issue. +1 this feature request, if you want this implemented.
https://issuetracker.google.com/issues/143913035
Workarounds from the tracker issue creator:
If a validation rule is manually created with a NamedRange via the Sheets GUI, it can then be copied programmatically using Range.getDataValidations(), and subsequently used to programmatically create new DataValidations. DataValidations created this way maintain their connection to the NamedRange, and behave like their manually created counterparts. This demonstrates that the functionality to 'use' NamedRanges for data validation rules is already possible with Apps Scripts, but not the option to 'create' them.
As a half-answer, if you want just validation and can live without the drop-down list of valid values, you can programmatically set a custom formula that references the named range. This reference to the named range will not get expanded in the AppsScript, so future changes to the Named Range's actual range will percolate to the validator. Like so:
mySheet.getRange('F5')
.setDataValidation(
SpreadsheetApp.newDataValidation()
.requireFormulaSatisfied(
'=EQ(F5, VLOOKUP(F5, ' + namedRange.getName() + ', 1))'
)
.setAllowInvalid(false)
.build()
);
(The formula just checks that the value in the cell being tested is equal to what VLOOKUP finds for that cell, in the first column -- I'm assuming the named range content is sorted.)
Use getRangeByName()
function lfunko() {
const ss = SpreadsheetApp.getActive();
const sh = ss.getSheetByName("Sheet0");
var cell = sh.getRange(1, 10);//location where datavalidation is applied
var rule = SpreadsheetApp.newDataValidation().requireValueInRange(ss.getRangeByName("MyList")).build();
cell.setDataValidation(rule);
}
So I started out using google scripts and sheets after departing from excel.
In excel, when you want to select a particular range using a variable, the formula in the macro will be
Range("C1:F" & lastrow).select
where lastrow is the variable that you have previously named.
I cannot find an equivalent formula or script that can do the same in google scripting.
Basically all I want is to select a particular range to copy, but because the data row will vary, I want to select only the used rows rather than just the entire page.
Thank you so much for your help, it was critical in helping me to find the right direction!
I managed to cobble together a code that basically mirrors the excel code of selecting the rows and columns that i need.
For some reason, I realised like google scripts are case sensitive but excel vb is not, so it is another thing that I did have to watch out for.
Basically, this is the equivalent of excel's macro for:
Sheets("MySheet").select
lastrow = Range("O99999").End(XLUp).row
Range("K1:V" & lastrow).select
Here is my code:
function zzz1() {
var sheet = SpreadsheetApp.getActive().getSheetByName('MySheet');
var lastrow = sheet.getRange("O"+(sheet.getLastRow()+1)).getNextDataCell(SpreadsheetApp.Direction.UP).getRow();
var printrange = sheet.getRange("K1:V" + lastrow)
printrange.activate()
}
Using formulas
You can use the =INDIRECT() function, along with Google Sheets concatenation.
Returns a cell reference specified by a string.
As an example, given the following "Student info" sheet:
You can get the first three students by using =INDIRECT("Student info!A2:B"&B1) from another sheet in the same Spreadsheet, as seen below:
Using Google Apps Script
You can use the getRange(a1Notation) method of the Class Sheet, along with JavaScript concatenation to obtain a range of your choice. As an example:
function myFunction() {
var sheet = SpreadsheetApp.getActive().getSheetByName('Student info');
var lastRow = 4;
var studentRange = sheet.getRange("A2:B" + lastRow);
Logger.log(studentRange.getValues());
}
This will obtain the range A2:B4 and print its values using the Logger.
Alternatively, you can also use the getRange(row, column, numRows, numColumns) variation of the method. The usage, in this case, would be as follows:
function myFunction() {
var sheet = SpreadsheetApp.getActive().getSheetByName('Student info');
var lastRow = 4;
var studentRange = sheet.getRange(2, 1, lastRow, 2);
Logger.log(studentRange.getValues());
}
Extra
In order to import data from another Spreadsheet you can use the =IMPORTRANGE() function. For a setup such as the one above but obtaining the data from a different Spreadsheet, the function could be used as follows:
I need to filter data from the latest sheet (a new one gets created every day automatically). The formula I use is
=FILTER('S&T 18/3/2019'!N:N;ISBLANK('S&T 18/3/2019'!N:N)=FALSE)
And it works, so in another cell I haveĀ“ve written another formula that keeps the first one up to date:
=CONCATENATE("=filter('S&T ";TEXT(TODAY();"d/m/yyyy");"'!N:N;ISBLANK('S&T";TEXT(TODAY();"d/m/yyyy");"'!N:N)=FALSE)")
In apps script I use the following code to paste the second formula as values, and it also works, but in its cell it shows as text instead of as a formula. If I manually delete the = form the beginning and then add it again it works perfectly. The idea is for it to work on its own. Can anyone help?
var spreadsheet = SpreadsheetApp.getActive();
spreadsheet.setActiveSheet(spreadsheet.getSheetByName('Test Filtro'), true);
spreadsheet.getRange('D1').activate();
spreadsheet.getRange('D1').copyTo(spreadsheet.getRange('E2'), SpreadsheetApp.CopyPasteType.PASTE_VALUES, false);
spreadsheet.getRange('E2').activateAsCurrentCell();
The Range#copyTo method accepts 2 optional arguments, the CopyPasteType and whether the data should be transposed. Your code fails to copy as a formula, because you use the CopyPasteType enum PASTE_VALUES. To copy a formula, you should use PASTE_FORMULA.
Enum CopyPasteType
PASTE_NORMAL Enum Paste values, formulas, formats and merges.
PASTE_FORMULA Enum Paste the formulas only.
PASTE_VALUES Enum Paste the values ONLY without formats, formulas or merges.
Your code would then look like:
...
var destCell = spreadsheet.getRange("E2");
spreadsheet.getRange("D1").copyTo(destCell, SpreadsheetApp.CopyPasteType.PASTE_FORMULA, false);
destCell.activateAsCurrentCell();
...
Since you are trying to do a "double paste" (your source data is a formula that creates a formula when it is evaluated, and you want to write the created formula), you need to paste the value of the original cell, then re-copy the output (your desired formula) and paste it as a formula:
...
const AS = SpreadsheetApp.CopyPasteType;
var destCell = spreadsheet.getRange("E2");
spreadsheet.getRange("D1").copyTo(destCell, AS.PASTE_VALUES, false); // Compute the desired formula, via formula-to-value conversion.
SpreadsheetApp.flush(); // Force the first copy to occur.
destCell.copyTo(destCell, AS.PASTE_FORMULA, false); // Activate the computed formula.
destCell.activateAsCurrentCell();
...
You may be able to avoid the first range copy entirely, by constructing the formula in script.
...
var TODAY = Utilities.formatDate(new Date(), "your timezone", "your format string here");
var myFormula = "=FILTER('S&T " + TODAY + "'!N:N;ISBLANK('S&T " + TODAY + "'!N:N)=FALSE)";
destCell.setFormula(myFormula);
...
Utilities.formatDate
In a Google Docs spreadsheet, I'm looking for something like =EVAL(A1) where A1 is set to "=1+2".
I found out that in MS Excel there is an EVALUATE() function (which seems a bit tricky to use properly). But I could not find anything similar in Google Docs.
I also searched through the function list, but could not find anything helpful...
No, there's no equivalent to Excel's EVALUATE() in Google Sheets.
There's long history behind this one, see this old post for instance.
If you're just interested in simple math (as shown in your question), that can be done easily with a custom function.
function doMath( formula ) {
// Strip leading "=" if there
if (formula.charAt(0) === '=') formula = formula.substring(1);
return eval(formula)
}
For example, with your A1, put =doMath(A1) in another cell, and it will be 3.
I know this an old post. I'm just wondering, why nobody suggested:
myCell.getValue();
This will give you the result of the formula in myCell (3 in your example).
If you want to write the result to the cell (instead of the formula), you could use:
function fixFormula(myCell) {
myCell.setValue(myCell.getValue());
}
Short answer
As was mentioned previously, Google Sheets doesn't have a built-in EVALUATE function, but Google Sheets could be extended to add this function. Fortunately some SocialCalc files could be used to make this easier.
Script
On Google spreadsheet I'm sharing my progress. At this time I added the SocialCalc files that I think that are required and a couple of functions, and several test cases.
NOTES:
Google Sheets specific functions like FILTER, UNIQUE, among others are not available in SocialCalc as well as other functions like SIGN.
I think that the SocialCalc file should be replaced by those on https://github.com/marcelklehr/socialcalc as it looks to be updated recently. H/T to eddyparkinson (see https://stackoverflow.com/a/16329364/1595451)
Uses
The EVALUATE function on the linked file could be used as a custom function.
Example 1
A1: '=1+2 (please note the use of an apostrophe to make the formula be treated by Google Sheets as a string.
B1 formula:
=EVALUATE(A1)
B1 display value:
3
Example 2
To "EVALUATE" a formula like =VLOOKUP(2,A1:B3,2), at this time we need to use the "advanced" parameters. See the following example:
B1: '=VLOOKUP(2,A1:B3,2)
C1 formula:
=EVALUATE(B1,"data","A1:B3")
C1 display value:
B
Code.gs
/**
*
* Evaluates a string formula
*
* #param {"=1+1"} formula Formula string
* #param {"Tests"} sheetName Target sheet.
* #param {"A1"} coord Target cell.
*
* #customfunction
*
*/
function EVALUATE(formula,sheetName,coord){
// SocialCalc Sheet object
var scSheet = new SocialCalc.Sheet();
if(sheetName && coord){
// Pass values from a Google sheet to a SocialCalc sheet
GS_TO_SC(scSheet,coord,sheetName);
}
var parseinfo = SocialCalc.Formula.ParseFormulaIntoTokens(formula.substring(1));
var value = SocialCalc.Formula.evaluate_parsed_formula(parseinfo,scSheet,1); // parse formula, allowing range return
if(value.type != 'e'){
return value.value;
} else {
return value.error;
}
}
/**
*
* Pass the Google spreadsheet values of the specified range
* to a SocialCalc sheet
*
* See Cell Class on socialcalc-3 for details
*
*/
function GS_TO_SC(scSheet,coord,sheetName){
var ss = SpreadsheetApp.getActiveSpreadsheet();
if(sheetName){
var sheet = ss.getSheetByName(sheetName);
var range = sheet.getRange(coord);
} else {
var range = ss.getRange(coord);
}
var rows = range.getNumRows();
var columns = range.getNumColumns();
var cell,A1Notation,dtype,value,vtype;
// Double loop to pass cells in range to SocialCalc sheet
for(var row = 1; row <= rows; row++){
for(var column = 1; column <= columns; column++){
cell = range.getCell(row,column);
A1Notation = cell.getA1Notation();
value = cell.getValue();
if(cell.isBlank()){
dtype = 'b';
vtype = 'b';
} else {
switch(typeof value){
case 'string':
dtype = 't';
vtype = 't';
break;
case 'date':
case 'number':
dtype = 'v'
vtype = 'n';
break;
}
}
scSheet.cells[A1Notation] = {
datavalue: value,
datatype: dtype,
valuetype: vtype
}
}
}
}
formula1.gs
https://github.com/DanBricklin/socialcalc/blob/master/formula1.js
socialcalcconstants.gs
https://github.com/DanBricklin/socialcalc/blob/master/socialcalcconstants.js
socialcalc-3.gs
https://github.com/DanBricklin/socialcalc/blob/master/socialcalc-3.js
If you want to evaluate simple math(like A1: "(1+2)*9/3"), you can use query:
=query(,"Select "&A1&" label "&A1&" ''",0)
Basic math sent to query's select is evaluated by query.
Copy and paste the formulas:
Maybe you can copy and paste the formulas you need from "jQuery.sheet". Moved to:
https://github.com/Spreadsheets/WickedGrid
Looks to be all "open source"
Wont fix the issue
Also: The issue "Enable scripts to use standard spreadsheet functions" is marked as "Wont fix", see https://code.google.com/p/google-apps-script-issues/issues/detail?id=26
Ethercalc
there is a google like opensource spreadsheet called Ethercalc
GUI Code:
https://github.com/audreyt/ethercalc
Formulas: https://github.com/marcelklehr/socialcalc
Demo - on sandstorm:
https://apps.sandstorm.io/app/a0n6hwm32zjsrzes8gnjg734dh6jwt7x83xdgytspe761pe2asw0
In the case of evaluating a function like
"=GoogleFinance("usdeur","price",date(2013,12,1),date(2013,12,16))"
This can be done this without evaluate by directly referring to other cells like this:
=GoogleFinance(A10,"price",E3,E6)
Simple hack to evaluate formulas in google spreadsheet:
select cells or columns with formulas
go Edit -> Find and replace...
check "Also search in formulas"
replace "=" to "=="
replace back "==" to "="
in the same "Find and replace" window uncheck "Also search in formulas"
formulas will evaluate! :)
Thank you for user3626588's workaround here and it does indeed work. Based off your instructions it looks like it can be simplified even further.
In Cell B1 Enter the following:="=sum(A1:A5)"
In Cell C1 Set a data validation and select B1 with dropdown option.
Now select C1 and select the formula from the dropdown, it will sum any values between A1 through A5 automatically.
I have a sheet where I was creating a complicated formula for multiple values and this process worked!
Thank you once again as I was trying to avoid a script since I have data that is being pulled by another program on my worksheet. Script function do not always run automatically in those situations.
Here is the trick. Insert formula in the required cell, then get retrieve that cell value and replace the already inserted formula with this new value.
function calculateFormula(row, col){
var spreadsheet = SpreadsheetApp.getActive();
var sheet = spreadsheet.getSheetByName("Sheet Name");
sheet.getRange(row,col).setValue("=sum(D6,C12:C14)");
sheetData = sheet.getDataRange().getValues();
var newValue = sheetData[row-1][col-1];
sheet.getRange(row,col).setValue(newValue);
}
How about just converting a column of expressions which are not preceded by a "+"?
92/120
67/85
etc.
It's a bit of a hack, but this works
get the formula from the cell;
set the formula back again; then
get the value from the cell.
var cell = sheet.getRange("A1");
var formula = cell.getFormula();
cell.setFormula(formula);
var fileCell = cell.getValue();
Awesome work around for google not having evaluate(). I have looked all around and besides script have found no other way to have a formula as a string on one sheet then use that formula on another. In fact everything I've seen says you can't. Would be helpfull if anyone reading this could repost around if they come to an appropriate question since I must have read a half dozen posts saying it wasn't possible before I just rolled up my sleaves and done done it. :) It still has a little clunkyness since you need two cells in the spreadsheet you want the formula to execute, but here goes.
Ok, some set up. We'll call the spreadsheet with the formula as string SpreadsheetA, call the tab the formula is on TabAA, the Spreadsheet you want to call and execute said formula SpreadsheetB. I'll use a multi-tab example, so say you want the sum of A1:A5 on SpreadsheetB tab: TabBA to be calculated on SpreadsheetB tab: TabBB cell A1. Also call the URL of spreadsheet A: URLA
So, in Spreadsheet A Tab: TabAA cell A1 put ="=sum(TabBB!A1:A5)", therefore the cell will display: =sum(A1:A5). Note: you don't need any $ in formula. Then in Spreadsheet B, Tab: TabBB, cell A2 put: =Query(Importrange("URLA","TabAA!A1"),"select Col1 where Col1 <> ''"). That cell will now display =sum(TabBA!A1:A5). Next to that, cell A1 of Spreadsheet B tab: TabBB, create a dropdown of the cell with the formula in B2 (right click cell A1, select data validation, for Criteria select: List from range, enter B2 in box to right). That cell should now be summing SpreadsheetB, TabBA, range A1:A5
Hope that was clear, I'm rather novice at this. Also important, obviously you would only do this in cases where you wanted to choose from multiple formulas on spreadsheetA, instead of TabAA!A1 say you had another formula in A2 also so your query would be =Query(Importrange("URLA","TabAA!A1:A2"). I understand in the simplistic case given you would simply put the formula where you needed the sum.
Edit: Something I noticed, was when I wanted to use a formula with double quotes the above scenario didn't work because when you wrapped the formula with double quotes in double quotes you get an error since you need single quotes inside double quotes. The example I was trying: if(counta(iferror(query(B15:C,"select C where C = 'Rapid Shot' and B = true")))>0,Core!$C$18+$C$10&" / ",)&Core!$C$18+$C$10&if(Core!$C$18>5," / "&Core!$C$18-5+$C$10,)&if(Core!$C$18>10," / "&Core!$C$18-10+$C$10,)&if(Core!$C$18>15," / "&Core!$C$18-15+$C$10,)
In that case I put another formula into Spreadsheet A TabAA cell A2 that read ="="&A1. Then, ajusted the importrange referance in spreadsheet B to reference that cell instead.
BTW, this absolutly works so if you can't get it let me know where your having problems, I don't do a lot of colaboration so maybe I'm not saying something clear or using the right / best terminollagy but again I've seen many posts saying this was impossible and no one saying they had found another way.
Thanx ~ K to the D zizzle.
Here is the working trick to evaluate the concatenated formula string. Use the formula cell as a data validation source for the target cell. Maybe it is not a fully automated solution. But evaluating refreshed formulas has been stripped down to just one click. You just need to reselect the value from the validation box when it is necessary. Many thanks to #Aurielle Perlmann and #user3626588 for the idea.
As an example, when you have set up dynamic multiple concatenations of such below formula in another sheet, this will work well with selecting validation option.
In my case, pressing enter twice is not userfriendly.
=({FILTER(IMPORTRANGE("https://docs.google.com/spreadsheets/d/aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/edit"; "EXPENSES!A2:P"); INDEX(IMPORTRANGE("https://docs.google.com/spreadsheets/d/aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/edit"; "EXPENSES!A2:P"); 0; 1) <> ""); FILTER(IMPORTRANGE("https://docs.google.com/spreadsheets/d/bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb/edit"; "EXPENSES!A2:P"); INDEX(IMPORTRANGE("https://docs.google.com/spreadsheets/d/bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb/edit"; "EXPENSES!A2:P"); 0; 1) <> ""); FILTER(IMPORTRANGE("https://docs.google.com/spreadsheets/d/cccccccccccccccccccccccccccccccccccccccccc/edit"; "EXPENSES!A2:P"); INDEX(IMPORTRANGE("https://docs.google.com/spreadsheets/d/cccccccccccccccccccccccccccccccccccccccccc/edit"; "EXPENSES!A2:P"); 0; 1) <> "")})
[enter image description here]
[enter image description here]
In a Google Docs spreadsheet, I'm looking for something like =EVAL(A1) where A1 is set to "=1+2".
I found out that in MS Excel there is an EVALUATE() function (which seems a bit tricky to use properly). But I could not find anything similar in Google Docs.
I also searched through the function list, but could not find anything helpful...
No, there's no equivalent to Excel's EVALUATE() in Google Sheets.
There's long history behind this one, see this old post for instance.
If you're just interested in simple math (as shown in your question), that can be done easily with a custom function.
function doMath( formula ) {
// Strip leading "=" if there
if (formula.charAt(0) === '=') formula = formula.substring(1);
return eval(formula)
}
For example, with your A1, put =doMath(A1) in another cell, and it will be 3.
I know this an old post. I'm just wondering, why nobody suggested:
myCell.getValue();
This will give you the result of the formula in myCell (3 in your example).
If you want to write the result to the cell (instead of the formula), you could use:
function fixFormula(myCell) {
myCell.setValue(myCell.getValue());
}
Short answer
As was mentioned previously, Google Sheets doesn't have a built-in EVALUATE function, but Google Sheets could be extended to add this function. Fortunately some SocialCalc files could be used to make this easier.
Script
On Google spreadsheet I'm sharing my progress. At this time I added the SocialCalc files that I think that are required and a couple of functions, and several test cases.
NOTES:
Google Sheets specific functions like FILTER, UNIQUE, among others are not available in SocialCalc as well as other functions like SIGN.
I think that the SocialCalc file should be replaced by those on https://github.com/marcelklehr/socialcalc as it looks to be updated recently. H/T to eddyparkinson (see https://stackoverflow.com/a/16329364/1595451)
Uses
The EVALUATE function on the linked file could be used as a custom function.
Example 1
A1: '=1+2 (please note the use of an apostrophe to make the formula be treated by Google Sheets as a string.
B1 formula:
=EVALUATE(A1)
B1 display value:
3
Example 2
To "EVALUATE" a formula like =VLOOKUP(2,A1:B3,2), at this time we need to use the "advanced" parameters. See the following example:
B1: '=VLOOKUP(2,A1:B3,2)
C1 formula:
=EVALUATE(B1,"data","A1:B3")
C1 display value:
B
Code.gs
/**
*
* Evaluates a string formula
*
* #param {"=1+1"} formula Formula string
* #param {"Tests"} sheetName Target sheet.
* #param {"A1"} coord Target cell.
*
* #customfunction
*
*/
function EVALUATE(formula,sheetName,coord){
// SocialCalc Sheet object
var scSheet = new SocialCalc.Sheet();
if(sheetName && coord){
// Pass values from a Google sheet to a SocialCalc sheet
GS_TO_SC(scSheet,coord,sheetName);
}
var parseinfo = SocialCalc.Formula.ParseFormulaIntoTokens(formula.substring(1));
var value = SocialCalc.Formula.evaluate_parsed_formula(parseinfo,scSheet,1); // parse formula, allowing range return
if(value.type != 'e'){
return value.value;
} else {
return value.error;
}
}
/**
*
* Pass the Google spreadsheet values of the specified range
* to a SocialCalc sheet
*
* See Cell Class on socialcalc-3 for details
*
*/
function GS_TO_SC(scSheet,coord,sheetName){
var ss = SpreadsheetApp.getActiveSpreadsheet();
if(sheetName){
var sheet = ss.getSheetByName(sheetName);
var range = sheet.getRange(coord);
} else {
var range = ss.getRange(coord);
}
var rows = range.getNumRows();
var columns = range.getNumColumns();
var cell,A1Notation,dtype,value,vtype;
// Double loop to pass cells in range to SocialCalc sheet
for(var row = 1; row <= rows; row++){
for(var column = 1; column <= columns; column++){
cell = range.getCell(row,column);
A1Notation = cell.getA1Notation();
value = cell.getValue();
if(cell.isBlank()){
dtype = 'b';
vtype = 'b';
} else {
switch(typeof value){
case 'string':
dtype = 't';
vtype = 't';
break;
case 'date':
case 'number':
dtype = 'v'
vtype = 'n';
break;
}
}
scSheet.cells[A1Notation] = {
datavalue: value,
datatype: dtype,
valuetype: vtype
}
}
}
}
formula1.gs
https://github.com/DanBricklin/socialcalc/blob/master/formula1.js
socialcalcconstants.gs
https://github.com/DanBricklin/socialcalc/blob/master/socialcalcconstants.js
socialcalc-3.gs
https://github.com/DanBricklin/socialcalc/blob/master/socialcalc-3.js
If you want to evaluate simple math(like A1: "(1+2)*9/3"), you can use query:
=query(,"Select "&A1&" label "&A1&" ''",0)
Basic math sent to query's select is evaluated by query.
Copy and paste the formulas:
Maybe you can copy and paste the formulas you need from "jQuery.sheet". Moved to:
https://github.com/Spreadsheets/WickedGrid
Looks to be all "open source"
Wont fix the issue
Also: The issue "Enable scripts to use standard spreadsheet functions" is marked as "Wont fix", see https://code.google.com/p/google-apps-script-issues/issues/detail?id=26
Ethercalc
there is a google like opensource spreadsheet called Ethercalc
GUI Code:
https://github.com/audreyt/ethercalc
Formulas: https://github.com/marcelklehr/socialcalc
Demo - on sandstorm:
https://apps.sandstorm.io/app/a0n6hwm32zjsrzes8gnjg734dh6jwt7x83xdgytspe761pe2asw0
In the case of evaluating a function like
"=GoogleFinance("usdeur","price",date(2013,12,1),date(2013,12,16))"
This can be done this without evaluate by directly referring to other cells like this:
=GoogleFinance(A10,"price",E3,E6)
Simple hack to evaluate formulas in google spreadsheet:
select cells or columns with formulas
go Edit -> Find and replace...
check "Also search in formulas"
replace "=" to "=="
replace back "==" to "="
in the same "Find and replace" window uncheck "Also search in formulas"
formulas will evaluate! :)
Thank you for user3626588's workaround here and it does indeed work. Based off your instructions it looks like it can be simplified even further.
In Cell B1 Enter the following:="=sum(A1:A5)"
In Cell C1 Set a data validation and select B1 with dropdown option.
Now select C1 and select the formula from the dropdown, it will sum any values between A1 through A5 automatically.
I have a sheet where I was creating a complicated formula for multiple values and this process worked!
Thank you once again as I was trying to avoid a script since I have data that is being pulled by another program on my worksheet. Script function do not always run automatically in those situations.
Here is the trick. Insert formula in the required cell, then get retrieve that cell value and replace the already inserted formula with this new value.
function calculateFormula(row, col){
var spreadsheet = SpreadsheetApp.getActive();
var sheet = spreadsheet.getSheetByName("Sheet Name");
sheet.getRange(row,col).setValue("=sum(D6,C12:C14)");
sheetData = sheet.getDataRange().getValues();
var newValue = sheetData[row-1][col-1];
sheet.getRange(row,col).setValue(newValue);
}
How about just converting a column of expressions which are not preceded by a "+"?
92/120
67/85
etc.
It's a bit of a hack, but this works
get the formula from the cell;
set the formula back again; then
get the value from the cell.
var cell = sheet.getRange("A1");
var formula = cell.getFormula();
cell.setFormula(formula);
var fileCell = cell.getValue();
Awesome work around for google not having evaluate(). I have looked all around and besides script have found no other way to have a formula as a string on one sheet then use that formula on another. In fact everything I've seen says you can't. Would be helpfull if anyone reading this could repost around if they come to an appropriate question since I must have read a half dozen posts saying it wasn't possible before I just rolled up my sleaves and done done it. :) It still has a little clunkyness since you need two cells in the spreadsheet you want the formula to execute, but here goes.
Ok, some set up. We'll call the spreadsheet with the formula as string SpreadsheetA, call the tab the formula is on TabAA, the Spreadsheet you want to call and execute said formula SpreadsheetB. I'll use a multi-tab example, so say you want the sum of A1:A5 on SpreadsheetB tab: TabBA to be calculated on SpreadsheetB tab: TabBB cell A1. Also call the URL of spreadsheet A: URLA
So, in Spreadsheet A Tab: TabAA cell A1 put ="=sum(TabBB!A1:A5)", therefore the cell will display: =sum(A1:A5). Note: you don't need any $ in formula. Then in Spreadsheet B, Tab: TabBB, cell A2 put: =Query(Importrange("URLA","TabAA!A1"),"select Col1 where Col1 <> ''"). That cell will now display =sum(TabBA!A1:A5). Next to that, cell A1 of Spreadsheet B tab: TabBB, create a dropdown of the cell with the formula in B2 (right click cell A1, select data validation, for Criteria select: List from range, enter B2 in box to right). That cell should now be summing SpreadsheetB, TabBA, range A1:A5
Hope that was clear, I'm rather novice at this. Also important, obviously you would only do this in cases where you wanted to choose from multiple formulas on spreadsheetA, instead of TabAA!A1 say you had another formula in A2 also so your query would be =Query(Importrange("URLA","TabAA!A1:A2"). I understand in the simplistic case given you would simply put the formula where you needed the sum.
Edit: Something I noticed, was when I wanted to use a formula with double quotes the above scenario didn't work because when you wrapped the formula with double quotes in double quotes you get an error since you need single quotes inside double quotes. The example I was trying: if(counta(iferror(query(B15:C,"select C where C = 'Rapid Shot' and B = true")))>0,Core!$C$18+$C$10&" / ",)&Core!$C$18+$C$10&if(Core!$C$18>5," / "&Core!$C$18-5+$C$10,)&if(Core!$C$18>10," / "&Core!$C$18-10+$C$10,)&if(Core!$C$18>15," / "&Core!$C$18-15+$C$10,)
In that case I put another formula into Spreadsheet A TabAA cell A2 that read ="="&A1. Then, ajusted the importrange referance in spreadsheet B to reference that cell instead.
BTW, this absolutly works so if you can't get it let me know where your having problems, I don't do a lot of colaboration so maybe I'm not saying something clear or using the right / best terminollagy but again I've seen many posts saying this was impossible and no one saying they had found another way.
Thanx ~ K to the D zizzle.
Here is the working trick to evaluate the concatenated formula string. Use the formula cell as a data validation source for the target cell. Maybe it is not a fully automated solution. But evaluating refreshed formulas has been stripped down to just one click. You just need to reselect the value from the validation box when it is necessary. Many thanks to #Aurielle Perlmann and #user3626588 for the idea.
As an example, when you have set up dynamic multiple concatenations of such below formula in another sheet, this will work well with selecting validation option.
In my case, pressing enter twice is not userfriendly.
=({FILTER(IMPORTRANGE("https://docs.google.com/spreadsheets/d/aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/edit"; "EXPENSES!A2:P"); INDEX(IMPORTRANGE("https://docs.google.com/spreadsheets/d/aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/edit"; "EXPENSES!A2:P"); 0; 1) <> ""); FILTER(IMPORTRANGE("https://docs.google.com/spreadsheets/d/bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb/edit"; "EXPENSES!A2:P"); INDEX(IMPORTRANGE("https://docs.google.com/spreadsheets/d/bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb/edit"; "EXPENSES!A2:P"); 0; 1) <> ""); FILTER(IMPORTRANGE("https://docs.google.com/spreadsheets/d/cccccccccccccccccccccccccccccccccccccccccc/edit"; "EXPENSES!A2:P"); INDEX(IMPORTRANGE("https://docs.google.com/spreadsheets/d/cccccccccccccccccccccccccccccccccccccccccc/edit"; "EXPENSES!A2:P"); 0; 1) <> "")})
[enter image description here]
[enter image description here]