Google Spreadsheets Add old number with new number - google-apps-script

I am trying to add a number to an old number. For example A1 contains "5", and I write "10" into B1, then A1 should show "15".
When I type "10" in B1 again, then A1 should show "25", so A1 adds the previous number with the new number.
I dont want to do mental arithemtic every time.
Is this possible with Google Sheets?

I thought that in your situation when Google Apps Script is used, your goal might be able to be achieved. The sample script is as follows.
Sample script:
Please copy and paste the following script to the script editor of Google Spreadsheet, and save the script.
function onEdit(e) {
const range = e.range;
if (range.getA1Notation() != "B1") return;
const [a, b] = range.offset(0, -1, 1, 2).getValues()[0];
range.offset(0, -1).setValue(a + b);
}
Testing:
When you use this script, please put a number to the cell "B1". By this, the script is automatically run by firing the OnEdit trigger as follows. So when you directly run the script with the script editor, an error occurs because the event object is not declared. Please be careful this.
Note:
This is a simple sample script from your question. So when your actual situation is different from your question, please modify the above script.
Reference:
Simple Triggers

Related

Google Sheets, how to run function every x column?

I have a script in google sheets with the following function:
// Function to get current active sheet-name.
function getsheetName(dummy) {
return SpreadsheetApp.getActiveSpreadsheet().getActiveSheet().getName();
}
Currently this function runs with this code in sheets:
=getsheetname(3:55)
The reference targets my entire sheet.
So whenever I make a change to a cell in my sheet the function runs again. This causes a huge amount of loading everytime i type anything in a new cell. Can i somehow reference the function to only run when i make changes to every x column instead of every cell?
I tried changing the formula but it would just stop updating completely, tried combining strings and using the MOD operator but I couldn't figure it out (keep in mind i am very new at this so probably missing something in my tinkering).
Appreciate any help!
I believe your goal is as follows.
You want to refresh the custom function of =getsheetname() when the columns "J", "T",,, (every 10 columns).
In this case, how about the following sample script? In order to refresh the function on Google Spreadsheet, I used this method. Ref
Sample script:
In this sample, in order to refresh your custom function, the simple trigger of onEdit is used. Please copy and paste the following script to the script editor of Spreadsheet. And, please save the script. When you use this script, please edit the columns "J", "T" and so on. By this, the script is run.
function onEdit(e) {
if (e.range.columnStart % 10 != 0) return;
const functionName = "=getsheetName";
const temp = "=temp";
const sheet = e.source.getActiveSheet();
sheet.createTextFinder(functionName).matchFormulaText(true).replaceAllWith(temp);
sheet.createTextFinder(temp).matchFormulaText(true).replaceAllWith(functionName);
}
In this case, 3:55 of =getsheetname(3:55) is not required to be used. You can use just =getsheetname().
If you changed the function name of your custom function, please modify const functionName = "=getsheetName";.
Reference:
Simple Triggers

How to round a cell after user input in Google Sheets?

It should be a very simple function but I can't find anything that functions the way I need.
I want to have a cell where a number can be entered, then after its entered it is replaced by that number rounded to its nearest 0.25
For example:
I enter 5.26 into cell A1, after i press enter the cell now says 5.25
This should only happen with cell A1, so if i enter 5.26 elsewhere it will stay as 5.26
Any help? Thanks in advance and sorry if this a common question.
This can be achieve by using Google Apps Script and onEdit Trigger.
Follow these steps to achieve the desired goal.
In your Google Sheet, go to Tools -> Script editor.
Delete any code in the script editor and paste code provided below.
Click Save.
Go back to your Google Sheet and type numbers in cell A1.
Press enter and wait the value to change.
Code:
function onEdit(e) {
var range = e.range;
var input = e.value;
if(range.getA1Notation() == "A1" && !isNaN(input)){
var number = (Math.round(input * 4) / 4).toFixed(2);
range.setValue(number);
}
}
Demo:
Triggers let Apps Script run a function automatically when a certain
event, like opening a document, occurs. In your case, we need to use
onEdit since it runs automatically when a user changes the value of
any cell in a spreadsheet. Apps Script passes the
triggered function an event object that contains information about the
context in which the event occurred (usually named e).
In the demo above, I created a condition that will check if the edited cell is A1 and if the inputted value is number. If both satisfy the condition, the script will calculate the value and use range.setValue() to change the value of A1.
References:
Class Range
Range.setValue(value)
Simple Triggers
Event Object

Google Sheet Auto Select Drop Down First Item

Is it possible for a Google Sheet dropdown, to auto select the first item in the list onChange / onEdit?
I'm unable to complete this directly on the sheet (I could be missing something), and I don't know enough about the Google Sheep App Script environment to know if it's possible.
I'm assuming that using Google App Script, this could be done.
I have setup this demo sheet, with everything working (other than what I'm after ;-)
https://docs.google.com/spreadsheets/d/1qzRT8rikVUfpZVOmugebB2yVHdLv_60K_Jwvxi6fX0U/edit?usp=sharing
What I would really like, When a "Tool" is changed/selected, I would like the "Colors" dropdown to select the first item in the list.
So if you select "Pencil", "Blue" would be auto selected into the cel. At the moment, the cel stays blank, until the user selects something.
Thank you.
I believe your goal as follows.
When the dropdown list of the cells "B5:B10" and the dropdown list of the column "C" is updated, you want to set the 2nd value of the updated dropdown list.
For example, when the dropdown list of the cells "B5" is set to "Pencil", you want to set the dropdown list of the cells "C5" to "Blue".
You want to achieve this using Google Apps Script.
In this case, I would like to run the script using the OnEdit trigger of the simple trigger. The sample script is as follows.
Sample script:
Please copy and paste the following script to the script editor of your sample Spreadsheet. And, please change the dropdown list of the column "B". By this, the script is run by the OnEdit trigger.
function onEdit(e) {
const range = e.range;
const sheet = range.getSheet();
if (sheet.getSheetName() != "Sheet1" || range.columnStart != 2 || range.rowStart < 5 || range.rowEnd > 10) return;
const r = range.offset(0, 1);
const value = [...new Set(r.getDataValidation().getCriteriaValues()[0].getValues().flat())].filter(e => e != "--")[0];
r.setValue(value);
}
In this sample, when the script is run, the range of the updated data validation rule is retrieved from the column "C", and retrieve the 2nd value of the dropdown list from the range.
Note:
In this sample script, from your sample Spreadsheet, when the dropdown list of cells "B5:B10" are changed, the script is run. So when you want to expand this range, please modify above script.
This sample script is for your sample Spreadsheet. When you change the sample Spreadsheet, the script might not be able to be used. So please be careful this.
References:
Simple Triggers
getDataValidation()

How to protect conditional formatting in google sheet?

I have 2 CFs in a sheet that I would like to keep upon copy/pastes you can see the range and formulas below.
CF1 Range : B3:H1001
CF1 Formula : =($A3<>"")*(B3="") //This one higlights the empty cells in a given range
CF2 Range : A3:R1001 // This one highlights the row if the cell in R column is No.
CF2 Formula : =$R:$R="No"
Is there a way to protect these CFs or apply them again after copy paste ? Thanks !
When I copy paste from another range I am losing the Conditional formats that i have created. So I want them to stay like I formatted or I would like them to be applied again after the copy/paste.
From above replying, I could understand that you want to keep the conditional formats, which are =($A3<>"")*(B3="") for B3:H1001 and =$R:$R="No" for A3:R1001, even when the range is copied and pasted to B3:H1001 and A3:R1001.
If my understanding is correct, how about this answer? Please think of this as just one of several possible answers.
Issue and workaround:
In the current stage, unfortunately, there are no methods for directly protecting the conditional formats in Google Apps Script. So in this case, as a workaround, I would like to propose to overwrite the conditional formats when the change of conditional formats and cells using OnChange event trigger.
Flow:
The range is copied and the parameters of conditional formats are changed.
The script is automatically run by the OnChange event trigger.
The existing conditional formats are deleted and new conditional formats are set.
Usage:
1. Copy and paste sample script
Please copy and paste the following sample script.
Sample script:
Please set the sheet name.
function onChange(e) {
const sheetName = "Sheet1"; // Please set the sheet name.
if (e.source.getActiveSheet().getSheetName() != sheetName || e.changeType != "OTHER") return;
const sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName(sheetName);
var rules = sheet.clearConditionalFormatRules();
const rule1 = SpreadsheetApp.newConditionalFormatRule()
.setRanges([sheet.getRange("B3:H")])
.setBackground("green")
.whenFormulaSatisfied('=($A3<>"")*(B3="")').build();
const rule2 = SpreadsheetApp.newConditionalFormatRule()
.setRanges([sheet.getRange("A3:R")])
.setBackground("green")
.whenFormulaSatisfied('=$R:$R="No"').build();
sheet.setConditionalFormatRules([rule1, rule2]);
SpreadsheetApp.flush(); // This line might not be required.
}
In this sample script, 2 conditional formats in your question are set as the background color of green.
2. Install OnChange event trigger
Please install the OnChange event trigger to the function of onChange.
3. Test run
As a test run, please copy and paste the range in sheetName. By this, the script is run by the OnChange event trigger.
Note:
I think that OnEdit event trigger can be also used. But in this case, when the parameters of the conditional formats are changed, the event trigger is not run. So I used the OnChange event trigger.
References:
Installable Triggers
setConditionalFormatRules(rules)

Use Google Sheet Formula in Script

After each time a new entry is added to my google sheet I need to have a script validate a combination of cells then make sure the output of the validation has changed before sending an email. I know how to do the validation and provide the correct output using a formula in the spreadsheet and I know how to have the script check that field and run. This works when someone edits the sheet from the UI. The problem is the spreadsheet is not being updated via the UI (it's being done via a IFTTT recipe), so I don't think the validation field is recalculating before the script runs who means no email is sent.
The following formula and script work perfectly when it is updated via the UI. My question is - is there a way to calculate the "value" variable from the script below with the formula from the spreadsheet?
Formula which is in Cell "D2" of Sheet "state":
=IF((COUNTIF(INDEX(data!A1:D5032,(SUMPRODUCT(MAX((data!A:A="meloc")*(ROW(data!A:A))))),4),"entered")+COUNTIF(INDEX(data!A1:D5032,(SUMPRODUCT(MAX((data!A:A="youloc")*(ROW(data!A:A))))),4),"entered"))>0,9999999999999,1111111111111)
Script that works fine with onEdit trigger when sheet is edited via the UI:
function myNotification() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var value = ss.getSheetByName("state").getRange("D2").getValue();
if( value > 0 ) {
var last = ScriptProperties.getProperty("last");
value = value.toString();
if( value != last ) {
MailApp.sendEmail('trigger#recipe.ifttt.com', 'Status #'+value+'\n\n',
'1="not here", 9="here": '+value+'\n\n', {
cc: 'myemail#gmail.com'
});
ScriptProperties.setProperty("last", value);
}
}
}
what you found cannot be worked arround. currently those triggers do not get called when external code uses the spreadsheets or drive api to change contents.
if you need it to work realtime, its not possible. else if you can live with a 1 minute delay, you could use a recurring 1minute trigger to check if the last modified date has changed on the spreadsheet ( by comparing with previously stored on script properties).
if it changed, process the entire sheet again.