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

修改Excel批量保护工作表VBA宏 支持筛选、透视表、插入行

Excel批量工作表保护宏修改方案

核心需求

现有宏可实现全工作簿工作表批量加锁/解锁,需调整加锁规则,工作表锁定后仍允许三类操作:

  • 表格筛选
  • 数据透视表使用
  • 插入新增行
    修改时整合原有批量处理逻辑,以及手动录制的单表权限开放参数,无需额外冗余代码。

修改后完整VBA代码

Sub ProtectAllWorksheets()
    Application.ScreenUpdating = False
    Dim ws As Worksheet
    Dim Pwd As String
    Pwd = InputBox("请输入批量保护工作表的密码", "保护工作表")
    For Each ws In ActiveWorkbook.Worksheets
        ws.Protect Password:=Pwd, _
            DrawingObjects:=True, _
            Contents:=True, _
            Scenarios:=True, _
            AllowInsertingRows:=True, _
            AllowFiltering:=True, _
            AllowUsingPivotTables:=True
    Next ws
    Application.ScreenUpdating = True
End Sub

Sub UnProtectAllWorksheets()
    Application.ScreenUpdating = False
    Dim ws As Worksheet
    Dim Pwd As String
    Pwd = InputBox("请输入批量取消工作表保护的密码", "取消工作表保护")
    On Error Resume Next
    For Each ws In Worksheets
        ws.Unprotect Password:=Pwd
    Next ws
    If Err <> 0 Then
        MsgBox "密码输入错误,无法完成所有工作表的解锁操作。", vbCritical, "密码错误"
    End If
    On Error GoTo 0
    Application.ScreenUpdating = True
End Sub

使用说明

  • 运行ProtectAllWorksheets宏,在弹窗输入自定义密码,即可批量给所有工作表加锁,加锁状态下默认开放筛选、插行、数据透视表三类操作权限,其余编辑行为仍受保护限制
  • 运行UnProtectAllWorksheets宏,输入正确密码即可批量解锁所有工作表
  • 解锁时如果密码输入错误,会弹出错误提示,不会执行后续解锁操作
  • 代码保留屏幕更新关闭逻辑,批量处理过程无界面闪烁,运行流畅

内容的提问来源于stack exchange,提问作者K. Akl

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.27 15:54:18