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

如何将Google Sheets按日期自动隐藏行的脚本应用到多工作表

问题描述
  • 现有一段Google Sheets平台的Apps Script脚本,功能是根据A列日期与当前日期的差值自动隐藏超过10天的行,原脚本仅对名为Sheet1的工作表生效
  • 需求为调整脚本逻辑,使相同处理逻辑可批量应用到Sheet1、Sheet2……总计最多40个同命名规则的工作表
  • 原脚本代码如下:
function myFunction1(){

  const ss = SpreadsheetApp.getActive();
  const sh = ss.getSheetByName("Sheet1");
  const today = new Date();
  
  const date_values = sh.getRange('A1:A'+sh.getLastRow()).getValues().flat();
  
  date_values.forEach((d,index)=>{
                      
     var diffTime = Math.abs(today - d);  
     const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24));
     if (diffDays > 10){
        sh.hideRows(index+1);
     }
  })
}
适配批量工作表的修改版脚本
function myFunction1(){
  const ss = SpreadsheetApp.getActive();
  const today = new Date();
  // 遍历Sheet1到Sheet40共40个目标工作表
  for (let sheetIndex = 1; sheetIndex <= 40; sheetIndex++) {
    const targetSheetName = `Sheet${sheetIndex}`;
    const currentSheet = ss.getSheetByName(targetSheetName);
    // 对应名称的工作表不存在时直接跳过,避免报错
    if (!currentSheet) continue;
    const lastDataRow = currentSheet.getLastRow();
    // 工作表无有效数据时跳过处理
    if (lastDataRow < 1) continue;

    const dateValues = currentSheet.getRange('A1:A' + lastDataRow).getValues().flat();
    dateValues.forEach((cellValue, rowIndex) => {
      // 跳过A列非有效日期的单元格,避免计算异常
      if (!(cellValue instanceof Date) || isNaN(cellValue.getTime())) return;
      
      const diffTime = Math.abs(today - cellValue);
      const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24));
      if (diffDays > 10) {
        currentSheet.hideRows(rowIndex + 1);
      }
    })
  }
}
核心调整说明
  • 移除原脚本固定绑定Sheet1的逻辑,新增1-40的序号循环,自动匹配Sheet+序号格式的目标工作表
  • 增加工作表存在性校验:如果对应序号的工作表未创建,直接跳过,不会中断脚本执行
  • 增加空表校验:如果目标工作表没有数据行,跳过取值逻辑,避免范围参数非法报错
  • 增加无效值容错:自动跳过A列不是有效日期格式的行,避免日期差计算返回NaN导致逻辑错误
  • 原脚本的日期差计算规则、隐藏行判断阈值完全保留,和原脚本的业务逻辑一致

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.28 12:21:22