You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Google Sheets脚本优化:第3行日期匹配条件时触发For循环发邮件

优化后的Auto_Email脚本
  • 一次性读取第3行所有日期数据,避免循环内反复调用表格读取接口,执行效率提升显著
  • 预计算清零时分秒的今日、3天前日期,先筛选出第3行符合触发条件的日期及对应列索引,完全满足日期触发需求
  • 已移除所有WeekX格式变量,仅保留一组subject、msg变量
  • 多个重复IF语句简化为单个判断逻辑,后续第3行新增日期无需修改代码结构,可自动适配
  • 移除原代码中未定义的data2相关无效代码
function Auto_Email() {
  // 日期预处理函数:清零时分秒,避免时间部分导致比较误差
  function getClearDate(date) {
    const d = new Date(date);
    d.setHours(0, 0, 0, 0);
    return d;
  }

  const sSheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Sheet1");
  // 读取第4行及之后的所有有效行数据
  const data = sSheet.getRange(4, 1, sSheet.getLastRow() - 3, sSheet.getLastColumn()).getValues();
  // 一次性读取第3行所有值
  const row3Values = sSheet.getRange(3, 1, 1, sSheet.getLastColumn()).getValues()[0];
  
  // 计算触发条件的目标日期:今日、3天前
  const today = getClearDate(new Date());
  const threeDaysAgo = getClearDate(new Date(Date.now() - 3 * 24 * 60 * 60 * 1000));

  // 筛选第3行中符合触发条件的日期对应的列索引
  const targetCols = [];
  for (let col = 0; col < row3Values.length; col++) {
    const cellDate = row3Values[col];
    if (cellDate instanceof Date) {
      const clearCellDate = getClearDate(cellDate);
      if (clearCellDate.getTime() === today.getTime() || clearCellDate.getTime() === threeDaysAgo.getTime()) {
        targetCols.push(col);
      }
    }
  }

  // 提前获取附件,避免循环内重复读取
  const Files1 = DriveApp.getFilesByName('file.pdf');
  let file1; 
  if (Files1.hasNext()) {
    file1 = Files1.next().getAs(MimeType.PDF);
  } else {
    throw new Error("No file");
  }

  const sig = "";
  const bcc = "";

  // 遍历所有数据行
  for (let i = 0; i < data.length; i++) { 
    const row = data[i];
    const Email = row[8];
    const ccEmail = row[9];
    // 邮箱为空直接跳过当前行
    if (!Email) continue;

    // 遍历所有符合触发条件的目标列
    for (const col of targetCols) {
      // 对应行的判断列索引 = 第3行的列索引 + 12(和原逻辑对齐:K3对应row[22],10+12=22)
      const checkVal = row[col + 12];
      if (checkVal === 3 || checkVal === 0) {
        const weekDate = row3Values[col];
        // 仅用一组subject和msg变量
        const subject = "Week of " + weekDate;
        const msg = "Good morning, " + row[1] + "."
                  + "<br/><br/> Please submit your results for the week of " + weekDate + " to your supervisor by the end of the week." 
                  + "<br><br>Thank you,"
                  + sig;
        // 发送邮件
        GmailApp.sendEmail(Email, subject, '', {
          htmlBody: msg,
          cc: ccEmail,
          bcc: bcc,
          attachments: [file1]
        });
      }
    }
  }
}

内容的提问来源于stack exchange,提问作者EV83

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.07 00:27:02