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

App Script 如何一次性取消保护多个有重复规律的单元格范围?

按规律批量设置工作表可编辑区域解决方案

你需要的规律为「每8列取前4列作为可编辑范围,行固定为5-35行,从第3列(C列)开始循环」,可以直接用脚本批量实现,不用手动逐个添加范围:

Excel 环境(VBA方案)

  • 打开目标工作表,按Alt+F11调出VBA编辑器
  • 右键左侧工作簿名称,选择「插入」-「模块」
  • 粘贴以下代码到模块窗口:
Sub 批量设置可编辑区域()
    Dim ws As Worksheet
    Dim startCol As Integer, endCol As Integer
    Dim currentCol As Integer
    Dim editRng As Range
    
    Set ws = ActiveSheet ' 可替换为Sheets("你的工作表名称")指定表
    startCol = 3 ' C列对应列号3
    endCol = ws.UsedRange.Columns.Count ' 自动读取当前表最大使用列数
    
    ' 先将整张表所有单元格设为锁定
    ws.Cells.Locked = True
    
    ' 按8列步长循环设置可编辑区域
    For currentCol = startCol To endCol Step 8
        Set editRng = ws.Range(ws.Cells(5, currentCol), ws.Cells(35, currentCol + 3))
        editRng.Locked = False
    Next currentCol
    
    ' 保护工作表,如需设置密码改为ws.Protect("你的密码")即可
    ws.Protect
    MsgBox "设置完成,共生成" & (Int((endCol - startCol) / 8) + 1) & "块可编辑区域"
End Sub
  • 按F5运行代码即可直接生效。

Google Sheets 环境(Apps Script方案)

  • 打开目标表格,点击菜单栏「扩展程序」-「Apps Script」
  • 替换默认代码为以下内容:
function 批量设置可编辑区域() {
  const sheet = SpreadsheetApp.getActiveSheet();
  const protection = sheet.protect().setDescription('全局工作表保护');
  const startCol = 3;
  const endCol = sheet.getLastColumn();
  
  // 清空旧的可编辑范围
  const oldUnprotected = protection.getUnprotectedRanges();
  oldUnprotected.forEach(range => protection.removeUnprotectedRange(range));

  // 循环添加符合规律的可编辑范围
  for (let col = startCol; col <= endCol; col += 8) {
    // 参数依次为:起始行、起始列、行数、列数,5-35行共31行,每次取4列
    const editRange = sheet.getRange(5, col, 31, 4);
    protection.addUnprotectedRange(editRange);
  }

  // 设置保护范围仅所有者可编辑,可按需调整权限规则
  const owner = Session.getEffectiveUser();
  protection.addEditor(owner);
  protection.removeEditors(protection.getEditors().filter(user => user.getEmail() !== owner.getEmail()));
  SpreadsheetApp.getUi().alert('可编辑区域设置完成');
}
  • 点击顶部运行按钮,首次运行按提示完成授权即可生效。

提示:如果后续工作表列数新增,重新运行一次对应脚本即可自动更新可编辑范围,无需手动调整。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.12 19:06:00