Send email based on the sum of cells from a form submission in Google Sheets

佐手、 提交于 2019-12-11 18:37:07

问题


I have a form with a series of linear scale questions. The submission goes to a sheet where I want to get the total of their answers and if the figure is 40 or over send them email "A" and if it is 39 or below they get email "B".

Is there a way to sum columns B:G in the newly created row when the form is submitted, get the user's email address from column H and use the sum of B:G to determine which email is sent?

I've been through the App Script documentation a bunch of times and can't seem to get this up and running successfully.

Edited to add where I got to with this (realising that it is currently worthless):

function onFormSubmit(e){
  var emailSubject;
  var row = 1;
  var messageCore;
  var newUserEmailSent = "NO";
  var EMAIL_SENT = "YES";
  var sheet = SpreadsheetApp.getActiveSheet();
  var startRow = 2;
  var lastRowUsed = getFirstEmptyRowByColumnArray() -1;
  function getFirstEmptyRowByColumnArray() {
    var spr = SpreadsheetApp.getActiveSpreadsheet();
    var column = spr.getRange('A:A');
    var values = column.getValues();
    lastRowUsed.setFormula("=SUM(B1:G1)");
  }
}

回答1:


You made a good start. Please review the event object returned by an "on form submit" trigger. As that object contains all of the response data, you don't actually need to read what's in the sheet. Specifically, take note of the values property, which contains an array with values (answers) in the same order as they appear in the spreadsheet.

You can do all of your summing and control-flow (over or under 40) using those values. Then you can use MailApp to send the appropriate email.

Take a look at this example and make any adjustments you need.

function onFormSubmit(formResponse){
  var sum = 0;
  for (var i = 1; i <= 6; i++) { // Column B = 1, Column G = 6
    sum = sum + Number(formResponse.values[i]);
  }
  var emailAddress = formResponse.values[7]; // This is the value that will be in Column H
  var yourEmailAddress = "me@example.com"; // Will be used in the BCC field, in case you want to receive the emails too
  if (sum >= 40) {
    var emailASubject = "Email A Subject";
    var emailABody = "Email A Body";
    MailApp.sendEmail(emailAddress, emailASubject, emailABody, {bcc: yourEmailAddress});
  } else {
    var emailBSubject = "Email B Subject";
    var emailBBody = "Email B Body";
    MailApp.sendEmail(emailAddress, emailBSubject, emailBBody, {bcc: yourEmailAddress});
  }
}

I assume that your form responses are already being saved to your spreadsheet (that's a requirement), but don't forget to install the trigger as pictured below.



来源:https://stackoverflow.com/questions/49773518/send-email-based-on-the-sum-of-cells-from-a-form-submission-in-google-sheets

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!