简体   繁体   中英

How to get the active value from a cell in a Google spreadsheet on form submission?

I have made a google form that saves data in a spreadsheet, I am writing the code for such spreadsheet so it sends me an email with some data from it, however I am struggling to get one of the values. Column 4 (D) gets the email address from the sender, so I wanna recover that value to put it as a "replyTo" variable and be able to directly reply to whoever is enquiring.

This is my code so far:

function Initialize() {

  try {

    var triggers = ScriptApp.getProjectTriggers();

    for (var i in triggers)
      ScriptApp.deleteTrigger(triggers[i]);

    ScriptApp.newTrigger("EmailGoogleFormData")
      .forSpreadsheet(SpreadsheetApp.getActiveSpreadsheet())
      .onFormSubmit().create();

  } catch (error) {
    throw new Error("Please add this code in the Google Spreadsheet");
  }
}

function EmailGoogleFormData(e) {

  try {

    if (MailApp.getRemainingDailyQuota() > 0) {

      // You may replace this with another email address
      var email = "nico.pinera@filmmusiclive.com";

      /*********** Sender email address || I HAVE PROBLEMS HERE ***********/

      var replyTo, senderMail,ss,r_max;
      ss = SpreadsheetApp.getActiveSheet();
      //r_max = ss.getmaxRows();


      // Returns the active cell
      var range = ss.getActiveRange();
      senderMail = range.getValues()[3];


      // Enter your subject for Google Form email notifications
      var subject = "Parte de NNTT recibido"


      var key, entry,
        message = "<b>Hola pepito</b><br/>aa</br><br><br><br><br>",
        ss = SpreadsheetApp.getActiveSheet(),
        cols = ss.getRange(1, 1, 1, ss.getLastColumn()).getValues()[0];

      // Iterate through the Form Fields
      for (var keys in cols) {

        key = cols[keys];
        entry = e.namedValues[key] ? e.namedValues[key].toString() : "";            

        // Only include form fields that are not blank
        if ((entry !== "Sí") && (entry !== "") && (entry !== ",") && (entry.replace(/,/g, "") !== "Sí"))
          message += '<img src="" /><br/><br/>' + ' <b><u> ' + key + '</u></b>' + ' => ' + entry ;           


      }

      MailApp.sendEmail(email, replyTo, subject, message);
    }
  } catch (error) {
    Logger.log(error.toString());
  }
}

Does anyone have any idea of how can I get the active value from that cell? which would be whatever row in column D. Also, I did do it by finding the int of maxRows() and then finding the value of the cell of maxRows() and column D, however If I manually edit the spreadsheet (say I manually add a value in the last row), new form requests would be stored above that one and shifting it down. (If I edit row 12 and a new request comes in, my row moves down to 13 and the new one is stored in 12 and so on and so forth).

Short answer

If the required data for the email is included in the form response, instead of using a spreadsheet bounded script, use a form bounded script.

Explanation

Google Forms also could have bounded scripts. Those scripts could be triggered on form submission and the form submission responses are included in the event object as a Form Response object. See Google Form Events and Form Response .

Benefits

  • To have the responses data in one place, the form file, instead of two, the form file and a spreadsheet.
  • the responses are in a response object. There is no need to call the value from a cell and this could save a several lines of code and calls to the Google Apps Script services
  • the response object include the edit response URL that is not added to the spreadsheet by default.

Brief code example

Simplified version of the code posted at Sending Confirmation Emails from Google Apps Forms by Les Bell and adapted to add the email address submitted as response to the reply-to parameter

function sendConfirmationEmail(e) {
  // e is a Form Event object 

  // Edit this to set the subject line for the sent email
  var subject = "Registration Successful";

  // This will show up as the sender's name
  var sendername = "Your Name Goes Here";

  // This is the body of the registration confirmation message
  var message = "Thank you for registering.<br>We will be in 
                  touch.<br><br>";

  // response is a FormResponse 
  var response = e.response;

  var textbody, sendTo, bcc, replyTo;

  // Get the script owner's email address, in order to bcc: them
  bcc = Session.getActiveUser().getEmail();

  // Now loop around, getting the item responses and writing them 
  // into the email message
  var itemResponses = response.getItemResponses();
  for (var i = 0; i < itemResponses.length; i++) {
    var itemResponse = itemResponses[i];
    // If this field is the email address, then use it to fill in 
    // the sendTo variable
    // Check that your form item is named "Email Address" or edit to match
    if (itemResponse.getItem().getTitle() == "Email Address") {
      sendTo = itemResponse.getResponse();
      replyTo = sendTo;
    }
  }

  GmailApp.sendEmail(sendTo, subject, message, {
                       bcc: bcc,  
                       name: sendername,  
                       htmlBody: message,  
                       replyTo: replyTo
                     });
}

Complete Code

The below code was taken from Sending Confirmation Emails from Google Apps Forms by Les Bell. The URLs included as comments were removed and some breaklines were added to avoid the appearance of the horizontal scroll bar.

Its purpose is to send the submitted responses and the edit response URL to the email address captured in the form submission.

function setup() {

  /* First, delete all previous triggers */
  var triggers = ScriptApp.getProjectTriggers();

  for (var i in triggers) {
    ScriptApp.deleteTrigger(triggers[i]);
  }

  /* Then add a trigger to send an email on form submit */
  ScriptApp.newTrigger("sendConfirmationEmail")
  .forForm(FormApp.getActiveForm())
  .onFormSubmit()
  .create();
}

function sendConfirmationEmail(e) {
  // e is a Form Event object 

  // Edit this to set the subject line for the sent email
  var subject = "Registration Successful";

  // This will show up as the sender's name
  var sendername = "Your Name Goes Here";

  // This is the body of the registration confirmation message
  var message = "Thank you for registering.<br>We will be in touch.
                 <br><br>";
  message += "Your form responses were:<br><br>";

  // response is a FormResponse 
  var response = e.response;

  var textbody, sendTo, bcc;

  // Get the script owner's email address, in order to bcc: them
  bcc = Session.getActiveUser().getEmail();

  // Now loop around, getting the item responses and writing them 
  // into the email message
  var itemResponses = response.getItemResponses();
  for (var i = 0; i < itemResponses.length; i++) {
    var itemResponse = itemResponses[i];
    message += itemResponse.getItem().getTitle() +": " 
            + itemResponse.getResponse() + "<br>";
    // If this field is the email address, then use it to fill in 
    // the sendTo variable
    // Check that your form item is named "Email Address" or edit 
    // to match
    if (itemResponse.getItem().getTitle() == "Email Address") {
      sendTo = itemResponse.getResponse();
    }
  }

  message += "<br>If you wish to edit your response, please click on 
              <a href=\"" 
          + response.getEditResponseUrl() 
          + "\">this link</a>.";
  message += "<br><br>";
  textbody = message.replace("<br>", "\n");

  GmailApp.sendEmail(sendTo, subject, textbody,
                       {bcc: bcc, name: sendername, htmlBody: message});
}

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