简体   繁体   中英

Google Apps Script - Email when row in Google sheet is updated

I am a teacher and new to programing script. I have a sheet named 'Scores' in a Google spreadsheet that has a list of emails in column A and an array of data in the following columns. When any data in B:R is changed I would like to automatically send an email to the address listed in column A of the row that changed in this sheet that includes the data in that row and associated column headers.

Example. Send Email to address in 'A4' Subject line: Undated Scores A string of text as a greeting.

Create a table with 'column headers' and 'Row Data'

B1 - B4 C1 - C4 D1 - D4...to last column

Thanks

You will have to compose the subject and the message with the information found in data. The index for data is one less than the column number. If you wish to learn more about the onedit event object try adding console.log(JSON.stringify(e)) to the second line and it will print in the execution log. I like to use Utilties.formatString() when composing text mixed in with merged data.

//function will only run with you in the correct sheet and you edit any cell from b to r or 2 to 18
function sendEmailWhenBRChanges(e) {
  const sh=e.range.getSheet();
  const startRow=2;//wherever your data starts
  if(sh.getName()=='Your Sheet Name' && e.range.columnStart>1 && e.range.columnStart<19 e.range.rowStart>=startRow) {
    let data=sh.getRange(e.range.rowStart,1,1,18).getValues()[0];//data is now in a flattened array
    //compose subject and message here if you want html then use the options object
    GmailApp.sendEmail(data[0],Subject,Message);
  }
}

on edit event object

Note you will have to create an installable trigger because sending email requires permission. You can create the trigger programmatically using ScriptApp.newTrigger() or go to the triggers section of the new editor or the edit menu in the legacy editor and don't forget to put the e in the parameters section of the function declaration.

Also please note that you cannot run this function directly from the script editor because it requires the event object that it gets from the trigger.

I know this is what you asked for but your not going to like it because it will trigger the email to be send whenever to edit any of the columns. You will probably prefer changing it later to accommodate putting a column of checkboxes which can be used as buttons for sending the emails.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM