excel 保护和取消保护工作簿结构

axzmvihb  于 2023-03-04  发布在  其他
关注(0)|答案(2)|浏览(150)

我正在尝试创建一个宏来取消保护(这样我就可以运行我的一些宏),当宏成功运行时,再次保护工作簿结构+工作表,保护工作簿工作正常,直到我添加了工作簿结构的(取消)保护,它给我错误
运行时错误“1004”:应用程序定义或对象定义的错误
我不明白为什么有人知道吗
这是我用来(取消)保护的代码

For Each wsheet In ActiveWorkbook.Sheets
         wsheet.Unprotect (XYZ1!!), Structure:=False
Next wsheet

'----
 
For Each wsheet In ActiveWorkbook.Sheets
         wsheet.Protect (XYZ1!), Structure:=True
Next wsheet

一些建议/帮助将非常感谢!

lmvvr0a8

lmvvr0a81#

取消保护工作簿和工作表仅接受1个参数,即密码字符串。
Workbook Unprotect Property
所以你的代码可以是这样的:

Sub UnprotectWorkbookWorksheets()

    Dim ws As Worksheet
    Dim wb As Workbook
    
    Const strPassword As String = "XYZ1!!"
    
    Set wb = ThisWorkbook

    wb.Unprotect strPassword

    For Each ws In wb.Worksheets
         ws.Unprotect strPassword         
    Next ws

End Sub

“结构”选项仅在“保护”方法中可用。
Workbook Protect Property
因此,您的代码可能如下所示:

Sub ProtectWorkbookWorksheets()

    Dim ws As Worksheet
    Dim wb As Workbook
    
    Const strPassword As String = "XYZ1!!"
    
    Set wb = ThisWorkbook

    For Each ws In wb.Worksheets
         ws.Protect strPassword
    Next ws

    wb.Protect Password = strPassword, Structure = True, Window = False

End Sub
5us2dqdw

5us2dqdw2#

Private Sub UnprotectAllSheets()
Application.EnableCancelKey = xlDisabled
     For Each wsheet In ActiveWorkbook.Sheets
         wsheet.Unprotect (XYZ123!)
      Next wsheet
End Sub

Private Sub ProtectAllSheets()
Application.EnableCancelKey = xlDisabled
     For Each wsheet In ActiveWorkbook.Sheets
         wsheet.Protect (XYZ123!)
      Next wsheet
End Sub

Private Sub protect_wb_structure()

    Dim wbPRotect As Workbook
    Const strPassword As String = "XYZ123!"
    Set wbPRotect = ThisWorkbook
    wbPRotect.Protect Password = strPassword, Structure = False, Window = False

End Sub

Private Sub Unprotect_wb_structure()

    Dim wbunprotect As Workbook
    Const strPassword As String = "XYZ123!"
    Set wbunprotect = ThisWorkbook
    wbunprotect.Protect Password = strPassword, Structure = True, Window = False

End Sub

相关问题