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

Google Sheets脚本需求:行下移存历史、新增指定行及行保护

修正后的Google Apps Script脚本

以下是实现你需求的完整脚本,同时解决原脚本依赖选中单元格的问题:

function verify() {
  const sheet = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
  const targetRow = 17; // 操作的目标行号

  // 1. 将第17行及以下所有行下移1行,留存历史记录
  sheet.insertRowBefore(targetRow);

  // 2. 在第17行新增带复选框的行,并填充当日日期
  // 复制原第17行(现在为第18行)的复选框规则与格式到新行
  const originalRow = sheet.getRange(targetRow + 1, 1, 1, sheet.getLastColumn());
  const newRow = sheet.getRange(targetRow, 1, 1, sheet.getLastColumn());
  originalRow.copyTo(newRow, SpreadsheetApp.CopyPasteType.PASTE_DATA_VALIDATION, false);
  originalRow.copyTo(newRow, SpreadsheetApp.CopyPasteType.PASTE_FORMAT, false);
  
  // 填充当日日期到新行的指定列(此处为B列,可修改列号)
  newRow.getCell(1, 2).setValue(new Date());

  // 3. 为下移后的历史行设置编辑保护
  const historyRow = sheet.getRange(targetRow + 1, 1, 1, sheet.getLastColumn());
  const protection = historyRow.protect();
  
  // 仅保留所有者编辑权限
  protection.removeEditors(protection.getEditors());
  if (protection.canDomainEdit()) {
    protection.setDomainEdit(false);
  }
}

功能说明

  1. 历史行下移:通过insertRowBefore(targetRow)在第17行前插入空行,原17行及以下内容自动下移,直接完成历史记录留存。
  2. 新增带复选框的行:复制下移后第18行的「数据有效性(复选框)」和「格式」到新17行,确保复选框功能完全一致;同时在指定列填充当日系统日期。
  3. 历史行保护:为下移后的历史行创建编辑保护,移除所有普通用户的编辑权限,仅表格所有者可修改该行内容。

原脚本问题分析

原脚本依赖getActiveCell().getRow()获取操作行号,导致只有选中A17时才能触发正确逻辑。修正后的脚本直接指定目标行(17行)执行操作,无需依赖单元格选中状态,确保每次点击按钮都能稳定运行。


自定义调整提示

  • 若目标行不是17行,修改targetRow变量的值即可。
  • 日期填充列可通过修改newRow.getCell(1, 2)中的列号调整(1=A列,2=B列,以此类推)。
  • 如需保护所有历史行(而非单一行),可将historyRow的范围改为:sheet.getRange(targetRow + 1, 1, sheet.getLastRow() - targetRow, sheet.getLastColumn())。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.05 10:11:28