Search code examples
excelvbaexcel-2016

Protect and unprotect workbook structure


I am trying to create a macro to Unprotect (so I can run some of my macros) and when the macro ran successfully protect the workbook structure + worksheets again, protecting the workbooksheets works fine until I added the (un)protect of the workbook structure, it is giving me error

Run-time error '1004': Application-defined or object-defined error

and I do not understand why, anyone any ideas?

this is the code I am using to (un)protect

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

some advice/help would be much appreciated!


Solution

  •     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