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

基于单元格颜色设置Google Sheets保护,仅允许编辑黄色单元格

仅允许编辑黄色单元格的Google Sheets脚本实现

下面的脚本会自动处理指定范围(A7:Z100)的单元格保护:先解除原有保护,再锁定所有非黄色单元格,只开放符合条件的黄色单元格供编辑。

function setEditableYellowCells() {
  const sheet = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
  const targetRange = sheet.getRange("A7:Z100");
  const cellBackgrounds = targetRange.getBackgrounds();
  const sheetProtection = sheet.protect().setDescription("仅允许编辑黄色单元格");

  // 初始化权限:仅保留脚本运行者的编辑权限,避免混乱
  const currentUser = Session.getEffectiveUser();
  sheetProtection.addEditor(currentUser);
  sheetProtection.removeEditors(sheetProtection.getEditors());
  if (sheetProtection.canDomainEdit()) {
    sheetProtection.setDomainEdit(false);
  }

  // 筛选所有黄色单元格,标记为可编辑区域
  const editableCells = [];
  // 注意:此处#ffff00为标准黄色,若你的条件格式黄色不同,请替换为对应色值
  const targetYellow = "#ffff00";

  for (let rowIdx = 0; rowIdx < cellBackgrounds.length; rowIdx++) {
    for (let colIdx = 0; colIdx < cellBackgrounds[rowIdx].length; colIdx++) {
      if (cellBackgrounds[rowIdx][colIdx] === targetYellow) {
        // 转换为表格实际行列索引(从1开始)
        const editableCell = targetRange.getCell(rowIdx + 1, colIdx + 1);
        editableCells.push(editableCell);
      }
    }
  }

  // 应用保护规则:锁定非黄色单元格
  sheetProtection.setUnprotectedRanges(editableCells.length > 0 ? editableCells : []);
}

使用步骤

  • 打开目标Google表格,点击顶部菜单栏「扩展程序」→「Apps 脚本」
  • 清空编辑器默认代码,粘贴上述脚本,点击保存并命名项目(比如"YellowCellEditAccess")
  • 首次运行点击编辑器顶部「运行」按钮,按提示完成授权(需允许脚本访问你的表格数据)
  • (可选)设置自动触发:点击编辑器左侧「触发器」图标,添加触发器,选择setEditableYellowCells函数,触发事件选「从电子表格」→「打开时」,这样每次打开表格都会自动更新保护规则

注意事项

  • 确认黄色值匹配:如果你的条件格式黄色不是标准#ffff00,可临时在脚本中添加Logger.log(sheet.getRange("XX").getBackground())(替换XX为黄色单元格位置),运行后查看日志获取准确色值再替换
  • 若条件格式更新导致黄色单元格变化,需重新运行脚本或等待表格打开时自动触发更新
  • 仅脚本授权用户(即你)可修改保护规则,其他用户只能编辑黄色单元格

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.30 15:39:20