简体   繁体   中英

Google Sheets script to automatically locate cells with todays date, copy the whole row and send it via email

I've built a reporting tool with google forms, where everyday I fill the forms, and the responses go to a spreadsheet. The spreadsheet has timestamp on column A, and the rest of the columns are the answers to the questions from the form.

I'm trying to write a script that will send me everyday at a specific time an e-mail with an excel file/google sheet link, which will basically have a copy of all the answers from today's forms.(with the date stamp of the current day).

Can anyone help me get started with that?

Thanks in advance!

What you need is

  • a time trigger
  • retrieve the timestamps backwards and push the rows with today's date into a value range array
  • create a new spreadsheet
  • assign the value range to the new sheet
  • retrieve the URL of the new spreadsheet
  • incorporate the URL into the email to send

Here is a sample code incorporating this features, I encourage you to become more familiar with Apps Script, so that you can adapt this code to your needs:

function bindATimeTriggerToMe() {
  var sheet = SpreadsheetApp.openById("PASTE-ID-OF-SPREADSHEET").getSheetByName("PASTE-NAME-OF-SHEET");
  var timestamps = sheet.getRange(1,1,sheet.getLastRow(), 1).getValues();

  var today = new Date();
  var i;
  for (i = timestamps.length-1; i > 0; i--){
    var day = timestamps[i][0];
    if (day.setHours(0,0,0,0) != today.setHours(0,0,0,0)){
      var firstRow = i + 2;
      break;
    }
  }
  if (firstRow){
    var rows = sheet.getLastRow()-firstRow+1;
    var columns = sheet.getLastColumn();
    var values = sheet.getRange(firstRow, 1, rows, columns).getValues();
    var newSheet = SpreadsheetApp.create("results from "+ today);
    newSheet.getSheetByName("Sheet1").getRange(1, 1, rows, columns).setValues(values);
    var url = newSheet.getUrl();

    var recipient ="XXX@gmail.com";
    var subject = "results from " + today;
    var body = "Click on the following link: "+url;
    GmailApp.sendEmail(recipient, subject, body)
  }
}

I think, that you must start to write code.

First I recommend reading about Events from here . There you can find two triggers:

  • Google Sheets Events - Form Submit
  • Google Form Events - From Submit

Pay attention to the difference between two types of trigger: simple and installable

Chose one of them, and use it for triggering some MailApp.sendEmail() function

Then i highly recommend to read documentation of SpreadSheet, Sheet and Range classes and try to write some code. When you catch a problem - write here with a piece of code that didn't work and describe your problem.

Good luck!

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