Home > Software engineering >  Send an email when one cell in a column contains data, but not when it's deleted
Send an email when one cell in a column contains data, but not when it's deleted

Time:05-26

I would like an email to be sent when something is added to a cell anywhere in column K, but not when that cell is cleared. Is this possible? Here is what I have so far. The email sends okay when I edit cell K1 (it was limited to this single cell for testing) but it also sends an email when I clear this cell. Thank you for any advice, as you can see I'm mostly just guessing here.

function sendEmail() {
  var ss = SpreadsheetApp.getActiveSpreadsheet()
  var sheet4 = ss.getSheetByName('Copy');
  var emailAddress = sheet4.getRange(2,12).getValue();
  var subject = sheet4.getRange(2,13).getValue();
  var message = sheet4.getRangeList(['G1', 'G2', 'G3', 'G4', 'G5', 'G6', 'G7', 'G8'])
    .getRanges()
    .map(range => range.getDisplayValue())
    .join('\n');
MailApp.sendEmail(emailAddress, subject, message);
}

function onEdit(e) {
  if(e.range.rowStart === 1 && e.range.columnStart === 11) {
    var sh = e.source.getActiveSheet();
    if(sh.getName() === 'Copy') {
    sendEmail()
    }
  }
}

CodePudding user response:

Maybe add to the "if" that if the value is different to empty it will not execute the code

Not sure which row or range belongs to K, so I name it "Range_in_K"

if(e.range.rowStart === 1 && e.range.columnStart === 11 && Range_in_K != "")

CodePudding user response:

Piggybacking off Karla's answer, generally when you delete single values, the event object (e) is absent of a value key. Therefore,

Try:

function onEdit(e) {

  if (e.source.getActiveSheet().getName() === `Copy`) {
    if (e.range.rowStart === 1 && e.range.columnStart === 11) {
      if (`value` in e) sendEmail()
    }
  }
  
}
  • Related