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

锁定工作表单元格格式权限VBA代码需重启工作簿才生效的问题

工作表保护后格式设置权限需重启工作簿的问题

我在工作簿中编写了VBA代码,用于让用户在受密码保护的工作表上设置单元格格式:

Sub ProtectionOptions()
     
    'PURPOSE: Protect Worksheet But Allow User to Format Cells
    
    Dim myPassword As String
    
    'Input Password to Variable
    myPassword = "SSD84006"
    
    'Protect Worksheet (Allow Formatting Cells)
    ActiveSheet.Protect Password:=(myPassword), AllowFormattingCells:=True
        
    'Protect Worksheet (Allow Formatting Cells)
    ActiveSheet.Protect _
      Password:=(myPassword), _
      AllowFormattingCells:=True
     
End Sub

把这个子例程添加到其他例程后,不管加在哪个例程里,都必须重启工作簿才能启用格式设置权限。哪怕把它加到新建工作簿的代码里,也得重启工作簿才能让格式设置功能可用:

Sub Add_New_Briefing()
    Application.EnableEvents = False
    Call fileProtection(False, Worksheets("1900 01 01"))
    Worksheets("1900 01 01").Copy After:=Worksheets(Worksheets.Count)
    ActiveSheet.Name = InputBox("Briefing Sheet (Date of the Monday) " & vbNewLine & "In the format of YYYY MM DD" & vbNewLine & "So 23/12/2024 would be entered 2024 12 23" & vbNewLine & "Note - there are spaces either side of MM")
    
    Call fileProtection(True)
    Application.EnableEvents = True
End Sub

我还使用了以下保护代码:

Sub fileProtection(ByVal blnProtect As Boolean, Optional ByVal SpecificSheet As Object)
Dim ws As Worksheet
Const pw = "SSD84006"
With ThisWorkbook
    If blnProtect Then
        .Protect pw
    Else
        .Unprotect pw
    End If
    
    If SpecificSheet Is Nothing Then
        For Each ws In .Worksheets
            If blnProtect Then
                ws.Protect pw
            Else
                ws.Unprotect pw
            End If
        Next
    Else
        With SpecificSheet
            If blnProtect Then
                .Protect pw
            Else
                .Unprotect pw
            End If
        End With
    End If
End With
End Sub

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.18 01:22:20