Trigger for Google Sheets - google-apps-script

I have a Google Spreadsheet that will send me an email once a figure in a cell reaches a certain number. I tried setting up triggers, but it doesn't work for what I need.
I need some code to open up the spreadsheet every 2 hours and then check the cell. If the number is greater than what I want, then it emails me.
Does anyone have their own code that I can add to my email function that will do this?
Any help would be appreciated.

The following code will check the value inside a cell and if the number inside the cell is greater than your specified limit, it will send an alert to the given email address.
function sendEmail() {
// get the number in the specified cell. Here I used the cell B2 for reference
var sheet = SpreadsheetApp.getActiveSheet();
var rowNum = sheet.getRange('B2').getValue(); //take the value to rowNum
if(rowNum > your_number_limit ){
var message = 'This is your Alert email!'; // Second column
var subject = 'Your Google Spreadsheet Alert';
MailApp.sendEmail("youremailaddress", subject, message);
}
// Send Alert Email.
}
To check the value every 2 hours do the following
From the Script Editor,
choose Resources > Current project's triggers. You see a panel with the message No triggers set up. Click here to add one now.
Click the link that says No triggers set up. Click here to add one now.
Under Run, select the function you want executed on schedule.
Under Events, select Time-driven.
On the first drop-down list that appears, select Hour timer
set interval of hours for 2 hours.
Click Save.
To ensure that the script runs at the correct time for a particular time zone, click File > Properties, select a time zone and click Save.

Related

Google Form get Google Sheets Value

I've got a Google Form to enter deposits and withdrawals into a Google Sheet and then the ending balance is calculated so the user can balance their check book.
I'm trying to get the most recent balance to display on the Google Form by finding the last row with a balance that is in the 'Ending Balance' column.
It seems a script may be easiest but nothing seems to so what I need. Any advice or direction is appreciated.
Here's the sheet I have set up, it's connected to my form with the headers in row 2.
Google Sheet Image
You can
create a bound script attached to your destination spreadsheet
set up a installable trigger onFormSubmit that will fire every time a new form is submitted
access the newest form submission data with getLastRow()
Retrieve the values in column 11 (which contains your Ending balance)
Sample script:
function getMyBalance(){
var sheet=SpreadsheetApp.getActive().getActiveSheet();
var row=sheet.getLastRow();
var column=11;
var balance=sheet.getRange(row, column).getValue();
Logger.log(balance);
}

Fill cell based on another sheets value

I have a spreadsheet on Google sheets with 2 sheets, Sheet1 and Sheet2. On Sheet1 I have 2 columns (ID1 and Result1), in which are filled. On Sheet2 I have 2 columns (ID2 and Result2), in which ID2 is filled and Result2 is filled with the word "empty".
Sheet1 in my real spreadsheet is getting data from Google Forms, so every time Sheet1 receives a value on ID1 and Result1, it should search for the ID1 value on Sheet2's ID2 and when finding, paste Result1 value in Result2 in the row it's was found.
Result2 would then only be updated when there's new data on Sheet1 submitted from the form.
I created this editable form and spreadsheet to make it easier to understand (I also added a note explaining it in there). You can see the form here and the spreadsheet here.
In cell B2 of your second sheet I entered the following:
=VLOOKUP(A2,Sheet1!A:B,2,FALSE)
I guess VLOOKUP on Google-Sheets does allow reference across worksheets?
FYI, when entering the formula, after enter the first argument which is your look up criteria, you can click your sheet1 and highlight column A and B, then go back to your sheet2 (with the second argument automatically filled by the system) to finish the formula with the third (result range column position within the look up range) and fourth argument (TRUE for approximate match and FALSE for exact match) and hit Enter to exit the formula.
After looking through the current answers and comments I think I understand what you are looking for.
Answer:
You can do this in Google Apps Script by creating a function that is bound to your Google Form which collects the latest response and does the data processing, and making it run on Form submission.
Steps to take:
Firstly, on your Form, you will need to create a bound script. From the menu in the top right of the Form edit page, click ⋮ > Script editor, which will open a new script page.
From there you can make a script which will automatically do this for you, and make an Installable Trigger which runs when you need.
Code:
After opening the Script Editor, you will see a ready-to-edit function that looks like this:
function myFunction() {
}
Replace the entire script with the following code:
function onSubmit(e) {
var responses = FormApp.getActiveForm().getResponses();
var response = responses[responses.length - 1].getItemResponses();
var connectedSheet = SpreadsheetApp.openById('<your-sheet-id>').getSheets();
var sheet2 = connectedSheet[1];
var result2Column = sheet2.getRange('A1:A').getValues();
for (var i = 0; i < result2Column.length; i++) {
if (response[1] == result2Column[0]) {
sheet2.getRange('B' + (i +1)).setValue(response[0]);
}
}
}
Make sure to replace <your-sheet-id> with the unique ID of your Google Sheeet - you can find this in the URL of the sheet between the d/ and /edit like so:
https://docs.google.com/spreadsheets/d/<your-sheet-id>/edit
Run the script by pressing the play button (►) and authorise the application to run.
Then go to Edit -> Current Project's Triggers and set up a new installable trigger with the following settings:
Choose which function to run: onSubmit
Choose which deployment should run: Head
Select event source: From form
Select event type On form submit
Explanation:
This script will run each time a new form submission is made automatically - it will take the ID from the form response and search Sheet2 for it. If it's found, then the response given for result will be put in Sheet2 also, next to the corresponding ID.
References:
Google Apps Script Installable Triggers
do it simply like this:
=ARRAYFORMULA(IFERROR(VLOOKUP(A2:A, Sheet1!A:B, 2, 0)))
or reset by checkbox:

Google Apps Script to count number of emails received yesterday, that has certain label, then save # daily to spreadsheet

Basically what the title says, but I want to:
1) Automatically count the number of emails received to my gmail account, that has a certain label on it
2) Count once everyday, even if zero
3) And report daily to a Google Spreasheet
4) So I can make a monthly report like such:
Date / #
Date / #
Date / #
.
.
.
Total for October / #
Average per day / #
I'm sure this is piece of cake using Google Script for script gurus, but I have no clue. Please teach me!
Open a new Untitled spreadsheet and go to Tools -> open Script editor and paste the code given below.
function CountEmail()
{
var label = GmailApp.getUserLabelByName("LabelName");
var labelname = label.getName();
var mails = label.getThreads();
var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Sheet1");
var date = new Date();
sheet.appendRow([labelname,date,mails.length]);
}
To run the script daily you will need to set a project trigger in the app script.For that follow the steps given below:
Resources -> Current Project's Trigger -> Add trigger -> Time driven -> Hour timer -> select the time when you want the script to run.
The total number of emails and the average emails/day can be calculated in the spreadsheet itself by just using the Sum() function.
Referencing the code Suyash Gandhi has posted (citing it here in case it gets removed so there is no confusion).
NOTE: not my code!!! Credit to Suyash Gandhi
function CountEmail()
{
var label = GmailApp.getUserLabelByName("LabelName");
var labelname = label.getName();
var mails = label.getThreads();
var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Sheet1");
var date = new Date();
sheet.appendRow([labelname,date,mails.length]);
}
NOTE: not my code!!! Credit to Suyash Gandhi
See the picture below
What you see here are 2 threads, 1 email in the bottom one, 3 emails in the top one and 1 draft in the top one. That given code will return a 2 here. If you wish to count all 4 (or 5 if you want the draft) you will need to use Gmail API (see reference here).
I have a script that gets all emails (every message) for a specific time period and outputs the receive date, sender, recipient and title to a spreadsheet. This is the code that actually fetches the emails. The rest of the code is mostly creating files, generating the query string and reset the script if it runs too close to 6 minutes.
queriedMessages =
Gmail.Users.Messages.list(userInfo.mail,
{
'q': queryString,
'pageToken': execProperties.nextPageId
});
userInfo.mail is the email address you are fetching the emails from. This is simply written like this because the script can be run with any account
queryString is a string that is used to search for emails and is exactly the same as you use in the gmail search box. So you would have label:labelname
pageToken is a code of the page of the search (basically what is needed when you click the next page button in gmail). It is returned as part of this function so you would be able to access it from queriedMessages.nextPageToken. So if you get more than 1 page, then you will need it to access the rest of the messages.
Also, keep in mind that you are getting all the messages fitting the query, so if you do this daily, you may want to include a trigger. Also, keep in mind that functions firing from triggers ignore your timezone (known bug), but you can figure out how to create a query that works for only 1 day fairly easily. Personally I just grab +1 day on the beginning and the end and just filter those messages out.

How to add date to empty cell by default if none specified in Google Form, on form submit with App Script?

I have a time log form that has a date field I do not want to have to fill out every time as 90% of the time the date would be today's date. (Sometimes you will be entering something from another day and need to change it).
When an entry is added column A is always going to have something, so it should check to see if A is empty and if that same rows D is empty it will input today's date into D.
Some of the example's I have looked at were for onEdit of cell change it, but I could not get it to work with a form submit or even just have it automatically check all the cells in D and if empty put today's date (Only when B has value).
I have a function to sort the sheet right now that is called when on form submit/onEdit happens and would like to stick the new formula in the bottom of the same one (unless that is bad practice). The reason for this is less functions to have to add to the trigger list.
A: Timestamp | B: What | C: Paid? | D: Date
You can try using Date from Google spreadsheets function list which Google Sheets offers.
And, as mentioned in Custom Functions in Google Sheets, if the available functions aren't enough for your needs, you can also use Google Apps Script to write custom functions then use them in Google Sheets just like a built-in function.
To get started, guidelines for custom functions and samples can be found in the given documentations.
You can use Google Apps Script with onFormSubmit trigger which will populate the said cell with default date.
Here is a sample code which will populate the current date in Column 4 of the row in question.
function onFormSubmit(e) {
//edit responses sheet name
var responseSheetName = 'Form Responses 2';
//Edit colmn number, column in which the date has to be autopopulated
var column = 4;
//Get target row number
var row = e.range.rowStart;
//If no date, pouplate the cell with current date
if(!e.values[column-1]){
SpreadsheetApp.getActive().getSheetByName(responseSheetName).getRange(row, column).setValue(new Date())
}
}
In order to setup the above code, open the Spreadsheet which contains the form responses. Go Tools > Script Editor. This will open script editor window. Paste above code and edit the responseSheetName and column . Now Save it.
After saving it, setup an on form submit trigger.
To setup the trigger, follow these steps.
From the script editor, choose Resources > Current project's triggers.
Click the link that says: No triggers set up. Click here to add one now.
Under Run, select the name of function onFormSubmit which you want to trigger.
Under Events, select From spreadsheet.
Select On form submit
Optionally, click Notifications to configure how and when you will be contacted by email if your triggered function fails.
Click Save.

How to catch last update in sheet

I have three Google Forms which submit data to different sheet in Spreadsheet. Google Forms write time stamp in first column when data is submitted. My triggered function send the email notification on submit data to spreadsheet from GForm. I need a different content of notification depending on the sheet of the spreadsheet where data is submitted.
I think about this:
get last update of spreadsheet
switch first sheet to action sheet
find the date equals the last update data in action sheet
if date is not founded, switch to next sheet and find last update date
...
...
if date is founded
get name of action sheet
send content-associated notification
So, think it's too difficult. Of course I can create many spreadsheet with many scripts and each script will send different notification, but it is not ergonomic.
Thank you!
In the event coming from your forms you can get the timeStamp and the row number where the response is recorded. With both criteria I guess it shoudn't be too hard to find the right sheet, just examine this row number in every sheet and compare the time values, if there is a match then you get it !
You can get the values in the eventinfo like this:
Logger.log('row = '+e.range['rowEnd'] + ' timestamp = '+e.namedValues['Timestamp'] )
I didn't test further so please update here is it worked as expected (or not).
Maybe you can add an onEdit trigger:
function onEdit() {
var s = SpreadsheetApp.getActiveSheet();
var sheet_name = s.getName();
//you can also add a code to get row and col, timestamp, etc.
}
Note: haven't tested this code. I assume this is what you want.