【问题标题】:Sending out emails based on date in Google Sheets Scripts根据 Google 表格脚本中的日期发送电子邮件
【发布时间】:2020-01-03 08:38:19
【问题描述】:

我正在尝试创建一个脚本,它将为包含今天日期的每个单元格发送一封电子邮件。这是我目前所拥有的:

function email() {

   var ss = SpreadsheetApp.getActiveSpreadsheet();
   var sheet = ss.getSheets()[0];
   var rowCounter = 1;
     var limit = sheet.getLastRow();

  // Fetch the estimated dates & Today's date
  var estimatedReturnDateRange = sheet.getRange("F:F"); 
    var estimatedReturnDate = estimatedReturnDateRange.getCell(rowCounter, 1);
  var todayDateRange = sheet.getRange("S1"); 
  var todayDate = todayDateRange.getValue();


  // Check totals sales
  for(i=1; i<=limit; i++){

  if (estimatedReturnDate = todayDate){
      // Fetch the email address
      var emailAddress = "maxbkimmel@gmail.com";

      // Send Alert Email.
      var message = estimatedReturnDate; // Second column
      var subject = 'Your Google Spreadsheet Alert';
      MailApp.sendEmail(emailAddress, subject, message);


  }
  rowCounter++;
  estimatedReturnDate = estimatedReturnDateRange.getCell(rowCounter, 1);

  }  
  rowCounter =1;
}

这是我设想的脚本工作逻辑的方式:

estimatedReturnDate 最初抓取 F 列中的第一个单元格,这是一个日期列表。

tod​​ayDate 抓取包含今天日期的单元格 S1。

for 循环然后遍历工作表的所有行,并检查estimatedReturnDate = todayDate。 如果是,则会发送一封电子邮件,其中包含与今天日期匹配的行号。

然后,rowCounter 递增,estimatedReturnDate 设置为行中的下一个单元格,循环再次运行。

我遇到的问题是,当我运行此脚本时,无论estimatedReturnDate 是否与todayDate 匹配,都会为工作表中的每一行发送一封电子邮件。

有谁知道这是什么原因造成的?

【问题讨论】:

  • estimatedReturnDate = todayDate 应该是estimatedReturnDate == todayDate,我认为

标签: google-apps-script google-sheets


【解决方案1】:
function email() {
  var ss=SpreadsheetApp.getActive();
  var sheet=ss.getSheets()[0];//This is always the left most sheet but not necessarily the same sheet depending how users move the sheets around.
  var vA=sheet.getRange(1,5,sheet.getLastRow(),1).getValues()
  var dt=new Date();
  var toda=new Date(dt.getFullYear(),dt.getMonth(),dt.getDate()).valueOf();//midnight yesterday
  var tmro=new Date(dt.getFullYear(),dt.getMonth(),dt.getDate()+1).valueOf();//midnight today
  for(var i=0;i<vA.length;i++){
    var dt=new Date(vA[i][0]).valueOf();//date from column5 of spreadsheet
    //dt is between midnight yesterday and midnight today
    if(dt>=toda && dt<=tmro){
      var emailAddress = "maxbkimmel@gmail.com";
      var message = Utilities.formatDate(dt, Session.getScriptTimeZone(), "E MMM dd, yyyy");
      var subject = 'Your Google Spreadsheet Alert';
      MailApp.sendEmail(emailAddress, subject, message);
    }
  }  
}

Utilities.formatDate

Date Class

【讨论】:

  • 为什么整个for循环的vA[i][0]设置为[0],你能解释一下吗?
  • vA[i][0] 在哪里设置为 0。
  • 对不起,你能解释一下语法吗?第二个方括号表示什么,为什么设置为 0?
  • 因为范围只有一列,但即使是一列范围仍然是二维对象。看起来像 [[],[],[],...]。它是第 i 行的第一列。
猜你喜欢
  • 2022-11-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-12-15
相关资源
最近更新 更多