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

Google Sheets中按日期自动锁定过期行脚本求助

Google Sheets 自动锁定过期行脚本解决方案

以下是适配你需求的Google Apps Script代码,可实现根据每行日期自动锁定已过期的行:

function lockExpiredRows() {
  const sheet = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
  const dateColumn = 1; // 替换为你的日期所在列序号(A列=1,B列=2,以此类推)
  const startRow = 2; // 数据起始行(假设第1行是表头)
  const lastRow = sheet.getLastRow();
  const today = new Date();
  today.setHours(0, 0, 0, 0); // 重置当天时间为0点,避免时间部分干扰判断

  // 获取所有日期数据
  const dates = sheet.getRange(startRow, dateColumn, lastRow - startRow + 1, 1).getValues();

  // 遍历每行,判断并锁定过期行
  for (let i = 0; i < dates.length; i++) {
    const rowDate = new Date(dates[i][0]);
    rowDate.setHours(0, 0, 0, 0);
    
    // 如果日期早于今天,锁定该行
    if (rowDate < today) {
      const rowRange = sheet.getRange(startRow + i, 1, 1, sheet.getLastColumn());
      const protection = rowRange.protect();
      
      // 仅允许表格所有者编辑,可按需调整权限
      protection.removeEditors(protection.getEditors());
      if (protection.canDomainEdit()) {
        protection.setDomainEdit(false);
      }
    }
  }
}

使用步骤:

  • 打开你的Google表格,点击菜单栏「扩展程序」→「Apps Script」
  • 清空默认代码,粘贴上述脚本
  • 根据表格结构,修改dateColumn(日期所在列序号)和startRow(数据起始行)
  • 点击保存,给脚本命名(比如「LockExpiredRows」)
  • 点击运行按钮测试,首次运行需按提示完成授权
  • (可选)设置定时自动运行:点击左侧「触发器」图标,添加触发器,选择lockExpiredRows函数,设置触发频率(如每天一次)

注意事项:

  • 确保日期列单元格格式为「日期」类型,避免脚本解析错误
  • 若需保留特定用户编辑权限,可修改代码中权限设置部分,比如通过protection.addEditor("邮箱地址")添加指定编辑者

内容的提问来源于stack exchange,提问作者Vĩnh Phạm

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.01 21:37:08