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

Google Sheets按日期自动锁定列:仅开放当日列并指定编辑用户

Google Sheets 自动按日期管控列编辑权限方案

一、核心实现逻辑

通过Google Apps Script编写脚本,每日自动扫描表头日期,锁定所有列后仅开放当日日期对应列;同时给指定用户开放所有列的编辑权限,不受锁定限制。

二、步骤1:编写自动切换权限的脚本

  1. 打开目标Google表格,点击顶部菜单栏的扩展程序 > Apps 脚本
  2. 清空默认代码,粘贴以下脚本:
function autoToggleColumnPermissions() {
  const sheet = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
  const headerRange = sheet.getRange(1, 1, 1, sheet.getLastColumn());
  const headers = headerRange.getValues()[0];
  const today = new Date();
  // 格式化日期为与表头一致的格式(根据你的表头调整,示例为yyyy/mm/dd)
  const formattedToday = Utilities.formatDate(today, Session.getScriptTimeZone(), "yyyy/MM/dd");
  
  const protection = sheet.protect().setDescription("Auto-locked columns except today's date");
  // 获取所有编辑器,保留所有者和指定特殊用户(替换成你要指定的邮箱)
  const editors = protection.getEditors();
  const specialEditors = ["user1@example.com", "user2@example.com"];
  protection.removeEditors(editors);
  protection.addEditors(specialEditors);
  // 禁止域内用户编辑,仅所有者和指定用户可操作
  protection.setDomainEdit(false);
  
  // 遍历表头,找到当日日期对应的列
  let targetColumn = -1;
  for (let i = 0; i < headers.length; i++) {
    if (headers[i] === formattedToday) {
      targetColumn = i + 1; // 列号从1开始计数
      break;
    }
  }
  
  if (targetColumn !== -1) {
    // 开放当日日期对应列的编辑权限
    const range = sheet.getRange(1, targetColumn, sheet.getLastRow(), 1);
    protection.setUnprotectedRanges([range]);
  } else {
    // 未找到当日日期列时,锁定所有列
    protection.setUnprotectedRanges([]);
  }
}
  1. 修改脚本中的specialEditors数组,替换成需要授予特殊编辑权限的用户邮箱
  2. 调整日期格式化字符串"yyyy/MM/dd",确保和你表格表头的日期格式完全匹配(比如表头是2022-11-10,就改成"yyyy-MM-dd")

三、步骤2:设置每日自动执行触发器

  1. 在Apps脚本编辑器中,点击左侧的触发器图标(时钟形状)
  2. 点击添加触发器,按以下配置设置:
    • 选择要运行的函数:autoToggleColumnPermissions
    • 选择部署类型:时间驱动
    • 选择时间类型:日计时器
    • 选择时间窗口:比如上午9:00到10:00(根据你的需求设置每日执行时间)
  3. 点击保存,授权脚本所需的权限

四、步骤3:验证和测试

  1. 手动执行一次脚本:在Apps脚本编辑器中点击运行按钮,确认表格仅当日日期列可编辑,其他列锁定;用指定特殊用户账号打开表格,可编辑所有列
  2. 普通用户测试:用非指定用户账号打开表格,确认只能编辑当日对应列

注意事项

  • 确保表头的日期格式和脚本中的格式化字符串完全一致,否则无法匹配到对应列
  • 脚本需要的权限:编辑表格保护设置、管理编辑器权限,授权时需确认允许
  • 如果表格有多个工作表,需要修改脚本中的getActiveSheet()为指定工作表,比如getSheetByName("Sheet1")

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.13 06:25:27