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

如何设置年度触发的触发器,实现年份自动更新及表格数据复制提取?

实现每年1月1日自动触发的触发器及数据提取方案

一、创建自动适配年份的年度触发器

你之前用的.at(yyyy, 01, 01)是固定日期触发器,只能触发一次,没法自动更新年份。正确的思路是用重复触发的时间规则,指定每年1月1日执行,代码如下:

function createAnnualTrigger() {
  // 先清理同名旧触发器,避免重复创建
  const existingTriggers = ScriptApp.getProjectTriggers();
  for (let trigger of existingTriggers) {
    if (trigger.getHandlerFunction() === "myFunction") {
      ScriptApp.deleteTrigger(trigger);
    }
  }

  // 创建每年1月1日触发的永久触发器
  ScriptApp.newTrigger("myFunction")
    .timeBased()
    .everyYears(1) // 设置每年重复
    .inMonth(1) // 指定1月(注意这里月份是1-12,不是0-11)
    .onDay(1) // 指定1号
    .setTimeZone("Asia/Shanghai") // 替换成你的实际时区,比如"America/New_York"
    .create();
}

只需要手动执行一次createAnnualTrigger(),就能生成一个永久生效的年度触发器,每年1月1日会自动触发myFunction,完全不用手动修改年份。

二、编写myFunction实现表格复制与上个月数据提取

接下来在myFunction里完成核心逻辑:复制原表格,筛选出上个月的数据(1月1日触发时,上个月是去年12月,代码会自动处理跨年情况):

function myFunction() {
  // 替换成你的原表格ID和数据工作表名称
  const sourceSpreadsheetId = "你的原表格ID";
  const sourceSheet = SpreadsheetApp.openById(sourceSpreadsheetId).getSheetByName("数据工作表");

  // 计算上个月的起止日期(自动处理跨年)
  const today = new Date();
  const lastMonthStart = new Date(today.getFullYear(), today.getMonth() - 1, 1); // 上个月1号
  const lastMonthEnd = new Date(today.getFullYear(), today.getMonth(), 0); // 上个月最后一天

  // 复制原表格到指定文件夹(可选,不指定则默认存根目录)
  const destinationFolderId = "你的目标文件夹ID"; // 替换成目标文件夹ID
  const destinationFolder = DriveApp.getFolderById(destinationFolderId);
  const newSheetName = `${lastMonthStart.getFullYear()}年${lastMonthStart.getMonth()+1}月数据`;
  const copiedSpreadsheet = DriveApp.getFileById(sourceSpreadsheetId).makeCopy(newSheetName, destinationFolder);
  const copiedSheet = SpreadsheetApp.openById(copiedSpreadsheet.getId()).getSheetByName("数据工作表");

  // 提取并筛选数据(假设第一列是日期列,格式为Date类型)
  const allData = sourceSheet.getDataRange().getValues();
  const filteredData = allData.filter(row => {
    // 跳过表头或非日期行,可根据你的需求调整
    if (typeof row[0] !== "object" || !(row[0] instanceof Date)) return true;
    // 只保留上个月的数据
    return row[0] >= lastMonthStart && row[0] <= lastMonthEnd;
  });

  // 清空复制表内容,写入筛选后的数据
  copiedSheet.clearContents();
  copiedSheet.getRange(1, 1, filteredData.length, filteredData[0].length).setValues(filteredData);

  Logger.log(`操作完成:已生成${newSheetName}表格`);
}

关键细节说明:

  • 跨年处理:1月1日触发时,today.getMonth() -1会得到-1,此时new Date()会自动转换为去年的12月,完全不用额外判断年份。
  • 数据筛选:如果你的日期列不是第一列,记得把row[0]改成对应列的索引(比如第二列是row[1]);如果日期是文本格式,需要先转成Date类型再比较。
  • 权限问题:首次运行脚本时,需要授权允许脚本访问你的Drive和Spreadsheet。

三、最后检查

  1. 手动执行createAnnualTrigger()创建触发器,可在脚本编辑器的「触发器」页面查看是否创建成功。
  2. 可以手动运行myFunction测试数据提取逻辑是否正常。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.13 08:58:34