How to paste special values in google scripts? - excel

I have this cell that has a formula which constantly updates its value. If the value gets to a specified number (For example: 10), I want to record its value on a different cell (For example: B2).
I'm guessing something like this would work:
If (Cell A2 = 10) {
change cell B2 into 10
}
I tried it inputting this formula on B2:
=if(A2=10,"10","")
The problem is, once A2 changes again, B2 changes as well. Is there any way to prevent this?

See if this works for you.
=if(A2=10,"10",if (A2<> 10,"10"))
Sorry if I misunderstood the problem. Try pasting this in the script editor.
function onEdit(){
var ss = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet()
var target = ss.getRange("A1").getValue()//Sets the Target value i.e. 10
var r = ss.getRange(2,1) //gets A2 range
var val = r.getValue()// gets A2 value (in my test A2 is =F1 which is a calculated value(=D1*E1).
if(val==target){ //If the value = the target value
ss.getRange(2,2).setValue(val) //write the value to B2
}
}

Related

I have written a formula using a concatenate function how can i run that formula which I have created? [duplicate]

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]

Exceljs cell contains a function

I am trying to generate an Excel sheet using Exceljs on NodeJS.
I need to get a particular cell (E4) for which I have this code written.
var row = worksheet.getRow(4);
var compInfra = row.getCell(5);
The cell ('E4') contains a value as the result of a formula ('E4 = C4+D4'), which I have defined previously. C4 and D4 contain non zero numbers.
I need to use this resultant value of the formula in a subsequent statement as below:
row = worksheet.getRow(20);
row.getCell(5).value = compInfra * worksheet.getCell('A20');
I get no output on my Excel sheet at 'E20', since the value in 'E4' is a result of the formula.
If I choose any other cell with some value instead of a formula, I get the result correctly.
How do I address this issue.
Thanks in advance
worksheet.getCell('E4').value = { formula: 'C4+D4' };
worksheet.getCell('C4').value = 7;
worksheet.getCell('D4').value = 5;
https://github.com/exceljs/exceljs#formula-value

How to find DataValidation list for an Excel cell using EPPlus

I have a workbook with a number of cells that have data validation specified as a dropdown list of allowed values. Using EPPlus, I want to be able to get for each such cell, the list of allowed values.
So far I've got:
ExcelWorkSheet.DataValidations gives me an ExcelDataValidationCollection, which is a collection of IExcelDataValidation items for the worksheet.
Each IExcelDataValidation has an Address property of type ExcelAddress which presumably references all cells that have that validation rule.
The step I'm stuck on is finding if a given cell is one of the cells included in the ExcelAddress
Any takers?
I'm currently using EPPlus 3.1.1.0, but can upgrade to a more recent version if necessary.
UPDATE
I didn't explain this clearly enough. Here's my situation in more detail.
Assume column C has some cells with list data validation. Some cells allow, say, "A, B, C"; other cells allow "D, E, F" etc. The range of cells for each data validation list is not contiguous, so, for example:
C2, C4, C7-C10, C20 may allow "A,B,C"
C3, C5-C6", C15 may allow "D,E,F"
I'm trying to determine which cells allow "A,B,C" and which allow "D,E,F" etc.
ExcelWorksheet.DataValidations contains ExcelDataValidationList items, one with values "A,B,C", one with values "D,E,F", etc.
ExcelDataValidationList.Address for the list "A,B,C" contains an ExcelAddress whose Address property looks something like: "C4 C7:C10 C2 C20 ...".
I want to determine if a given cell (say C6) is included in the range specified by this address "C4 C7:C10 C2 C20 ...".
Of course, I can String.Split on whitespace, and parse each item in the resulting list. But I was hoping there would be some more direct way of doing this, e.g.
ExcelAddress.Contains("C6")
or
ExcelAddress.Contains(6, 2) // row 6 col 2 = C6
Almost there, just check the IExcelDataValidation's specific type. Tested with EPPlus 4.1.0.0:
using (var package = new ExcelPackage(new FileInfo(path)))
{
var sheet = package.Workbook.Worksheets[1];
var validations = sheet.DataValidations;
foreach (var validation in validations)
{
var list = validation as ExcelDataValidationList;
if (list != null)
{
var range = sheet.Cells[list.Formula.ExcelFormula];
var rowStart = range.Start.Row;
var rowEnd = range.End.Row;
// allowed values probably only in one column....
var colStart = range.Start.Column;
var colEnd = range.End.Column;
for (int row = rowStart; row <= rowEnd; ++row)
{
for (int col = colStart; col <= colEnd; col++)
{
Console.WriteLine(sheet.Cells[row, col].Value);
}
}
}
}
}
Test worksheet:
Output:
one
two
three

How to use plus or minus in a cell inside a formula in another cell

I'm trying to do some stuff with solver but the results I need, I need to put the operators to the formula in another cell.
So, to be pratical, should be some like this:
A1 = <
A2 = >
A3 = <=
A4 = >=
B1 = 20
B2 = 30
C1 = =B1&A1&B2
The formula needs to understand the the data inside A1 to A4 are operators.
Any ideas?
Thanks!
As far as I'm aware, you can't do this in the traditional sense. What you can however do, is the following.
Select cell "C1"
Go to the formulas tab
Define a name
Name it something descriptive, like "Eval1" or whatever
Refer it to =EVALUATE(Sheet3!$A2&Sheet3!A$1&Sheet3!$B2)
Be aware that this uses relative selection, writing =Eval1 in cell G2 would not work in this case because it would try and evaluate A2 & E1 & B2 but can work if you adapt the refer to of eval1 in the name manager.

creating a counter cell and static cells in excel

Problem:
I have a counter cell: A1 with a value of =COUNTIF(B:B;"FOO")
This gives me a current "count" of all instances of "FOO" in column B.
I have a value cell C1 with a formula of: =IF(B1="FOO";"FOO_" & A1;)
This gives me a result of FOO_1 if "FOO" only exists once in Column B
Question:
I want to be able to reference the value of A1 at the time I write out the contents to the cell of C1. When A1 updates, I do not want C1 to be modified. C2 should now take the update of A1 (which would now be 2) and C2 would be: FOO_2 for example:
A1 = 1
B1 = FOO
C1 = FOO_1
A1 = 2
B2 = FOO
C2 = FOO_2
C1 still remains FOO_1 based on the value of A1 before a new row was added to column B
Looking for an automated way to create an ID, like an increment value in MySQL, and not looking for a solution that involves a person copy / pasting..
The problem with your approach is that, A1 will always change to reflect the COUNT, you can't use a value that WAS. What else is going into the remaining cells in Column A that you could not use the Count in the adjacent row as #JMax suggests?
If you have to increment with fixed Counts, I would recommend you think of a simple macro on a change event of whichever cell you are wanting. For instance everytime you enter "FOO" or "BAR" or anything, it would do a COUNTIF of the Range in B:B and concatenate the result entering it in the adjacent C.
No reason to depend upon A1 at all, and it possibly changing.
This example may get you started. And the Countif may use a ';' for your version of Excel
It assumes you are doing data entry and then moving to the next cell down. It also checks whether you have already made an entry in the adjacent cell in C so it does not change the count if you revisit a cell.
Which means it will be wrong in that adjacent cell unless you delete the value in C first before making a change. Of Course If you have 4 FOOs and then delete one you will still have FOO_4 and it won't change so if you change the 4th FOO to BAR first delete FOO_4. If the Increment HAS to match actual counts for some other reason, I would not rely upon this for that.
Sub doIncrement()
If ActiveCell.Column = 2 And ActiveCell.Offset(-1, 1) = "" Then
ActiveCell.Offset(-1, 1) = ActiveCell.Offset(-1, 0) & "_" & WorksheetFunction.CountIf(Range("B:B"), (ActiveCell.Offset(-1, 0)))
Else: Exit Sub 'or do something else
End If
End Sub
Then call this in
Private Sub Worksheet_Change(ByVal Target As Range)
Call doIncrement
End Sub
If you want to stick to a formula solution, you can replace the A1 formula by:
=COUNTIF($B$1:B1;"FOO")
That would do the trick when you drag and drop your formula.

Resources