简体   繁体   中英

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

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

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.

在此处输入图片说明

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