如何在表单提交时从Google电子表格中的单元格中获取有效值?

时间:2016-02-06 11:31:46

标签: javascript google-apps-script google-sheets google-form

我已经制作了一个将数据保存在电子表格中的Google表单,我正在为这样的电子表格编写代码,因此它向我发送了一封包含其中一些数据的电子邮件,但是我很难获得其中一个值。第4列(D)从发件人处获取电子邮件地址,因此我想恢复该值以将其作为“replyTo”变量并且能够直接回复任何正在查询的人。

到目前为止,这是我的代码:

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());
  }
}

有没有人知道如何从该单元格中获取有效值?这将是D列中的任何行。 另外,我通过找到maxRows()的int然后找到maxRows()和D列的单元格的值来做到这一点,但是如果我手动编辑电子表格(比如我在最后一行手动添加一个值),新表单请求将存储在该表单上方并将其向下移动。 (如果我编辑第12行并且有一个新请求进入,我的行向下移动到13并且新行存储在12中,依此类推等等。)

1 个答案:

答案 0 :(得分:0)

简短回答

如果电子邮件所需的数据包含在表单回复中,而不是使用电子表格有界脚本,请使用表单有界脚本。

解释

Google表单也可能包含脚本。这些脚本可以在表单提交时触发,表单提交响应作为表单响应对象包含在事件对象中。请参阅Google Form EventsForm Response

优势

  • 要将回复数据放在一个地方,表单文件而不是两个表单文件和电子表格。
  • 响应位于响应对象中。无需从单元格中调用该值,这可以节省多行代码并调用Google Apps脚本服务
  • 响应对象包括默认情况下未添加到电子表格的编辑响应网址。

简要代码示例

Les Bell在Sending Confirmation Emails from Google Apps Forms发布的简化版代码,适用于添加作为回复参数提交的电子邮件地址

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
                     });
}

完整代码

以下代码取自Les Bell的Sending Confirmation Emails from Google Apps Forms。删除了包含在注释中的URL,并添加了一些细分线以避免出现水平滚动条。

其目的是将提交的回复和修改回复网址发送到表单提交中捕获的电子邮件地址。

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});
}