Google Sheets - How to Trigger a Script when a new text value is added to specific column?

by Sahelanthropus   Last Updated October 22, 2018 02:03 AM

I've built a sheet that generates messages for clients based on certain input data. The message appears in a cell in column B when all the required data has been entered. When a new text value is generated at column B I need this script to be activated:

    // This constant is written in column C for rows for which an email
// has been sent successfully.
var EMAIL_SENT = 'EMAIL_SENT';

/**
 * Sends non-duplicate emails with data from the current spreadsheet.
 */ 
function sendEmails2() {
  var sheet = SpreadsheetApp.getActiveSheet();
  var startRow = 2; // First row of data to process
  var numRows = sheet.getLastRow(); // Number of rows to process
  // Fetch the range of cells 
  var dataRange = sheet.getRange(startRow, 1, numRows, 3);
  // Fetch values for each row in the Range.
  var data = dataRange.getValues();
  for (var i = 0; i < data.length; ++i) {
    var row = data[i];
    var emailAddress = row[0]; // First column
    var message = row[1]; // Second column
    var emailSent = row[2]; // Third column
    if (emailSent != EMAIL_SENT) { // Prevents sending duplicates
      var subject = 'Cognitive Training Software Tailored To Your Audience';
      MailApp.sendEmail(emailAddress, subject, message);
      sheet.getRange(startRow + i, 3).setValue(EMAIL_SENT);
      // Make sure the cell is updated right away in case the script is interrupted
      SpreadsheetApp.flush();
    }
  }
}

I'm new to any sort of coding and could't figure out how to make this happen. I tried creating an installable trigger using onEdit but could no longer get anything to send. I appreciate the help :)



Related Questions


Which is better: onEdit or onChange trigger?

Updated August 14, 2018 16:03 PM

Google App Script - changeType "REMOVE_GRID"

Updated June 29, 2018 15:03 PM

save data in new column every day

Updated November 08, 2018 05:03 AM