简体   繁体   中英

While using Google Sheets, what code should I use to send an email when a row has been added and then when that row is edited?

I am so very new to coding but trying to add code to automatically email certain staff members when our programming Google sheet is updated. The instances for an email are: -a new row is added, meaning a new show has been added to our programming -a row has been edited, meaning new information has been added in specific columns for marketing, the show can go onsale, etc.

I've tried frankensteining a number of codes or altering a few samples. Either the code doesn't work (can't find the source is a common issue) or it sends an email EVERY TIME there's an edit anywhere on the sheet when I'm only concerned about certain columns.

The closest I've come is this code but it sends an email for EVERY edit. I just need when a row is added and when specific columns are edited.

function SendEmail() {
 var ActiveSheet = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
 var StartRow = 4;
 var RowRange = ActiveSheet.getLastRow() - StartRow + 1;
 var WholeRange = ActiveSheet.getRange(StartRow,1,RowRange,5);
 var AllValues = WholeRange.getValues();

 var message = "";
 for (i in AllValues) {
 var CurrentRow = AllValues[i];

 var EmailSent = CurrentRow[5];
 var Sender = CurrentRow[1];

  message =
    "A Show has been added."


  var setRow = parseInt(i) + StartRow;

}


 var SendTo = "myemail.com";

 var Subject = "Show Added on MySheet";

  MailApp.sendEmail({
      to: SendTo,
      subject: Subject,
      htmlBody: message,
});
}

Any help is much appreciated. Thank you.

onEdit(e) {
 const sh=e.range.getSheet();
 if(sh.getName()=='Your sheet name' && e.range.rowStart>3 && 
e.rangeColumnnStart<7) {
   SendEmail();
  }
}

function SendEmail() {
  const ss = SpreadsheetApp.getActive();
  const sh = ss.getActiveSheet();
  const sr = 4;
  const RowRange = sh.getLastRow() - sr + 1;
  const WholeRange = sh.getRange(sh, 1, RowRange, 6);
  const AllValues = WholeRange.getValues();
  const message = "A Show has been added.";
  const SendTo = "myemail.com";
  const Subject = "Show Added on MySheet";
  for (let i=0;i<AllValues.length;i++) {
    let CurrentRow = AllValues[i];
    let EmailSent = CurrentRow[5];
    let Sender = CurrentRow[1];
    let setRow = parseInt(i) + sr;
    if(CurrentRow[5]!='Sent') {
      MailApp.sendEmail({to: SendTo,subject: Subject,htmlBody: message});
      sh.getRange(i+sr,6).setValue('Sent');
    }
  }
}

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