Macros don't work when sheet is protected. Running macro returns run-time error 1004

后端 未结 2 771
自闭症患者
自闭症患者 2021-01-15 04:10

I have three macros in my workbook that work fine. However, when I protect any of the worksheets, they stop to work and I get a run-time error 1004.

I

相关标签:
2条回答
  • 2021-01-15 04:30

    help for macro beginners:

    if you are using a button to run a macro, include the following inside sub buttonclick()

    Dim sh As Worksheet
    
    Dim yourPassword As String
    
        yourPassword = "whatever password you like"
    
       For Each sh In ActiveWorkbook.Worksheets
            sh.Unprotect Password:=yourPassword
    

    "now enter your macro which needs to be run

    ,at the end , before end sub paste the below line

    For Each sh In ActiveWorkbook.Worksheets
            sh.Protect Password:=yourPassword
        Next sh
    
    0 讨论(0)
  • 2021-01-15 04:31

    You don't have any code in there to unprotect at the start of the macro and then protect again at the end. You need something like this at the start (I think you already know this but just trying to be clear).

    SheetName.Unprotect Password:=yourPassword
    

    And this at the end:

    SheetName.Protect Password:=yourPassword
    

    You say you've tried this already but it's not clear from the code you posted where you had these commands.

    From trying to reproduce the behaviour at this end I notice you have two different worksheets you refer to as historyWks which could be causing problems with locking and unlocking.

    One option is to unprotect all worksheets at your entry point then protect them again at the exit.

    Private Const yourPassword As String = "password"
    
    Sub UnprotectAll()
        Dim sh As Worksheet
        For Each sh In ActiveWorkbook.Worksheets
            sh.Unprotect Password:=yourPassword
        Next sh
    End Sub
    
    Sub ProtectAll()
        Dim sh As Worksheet
        For Each sh In ActiveWorkbook.Worksheets
            sh.Protect Password:=yourPassword
        Next sh
    End Sub
    

    You just need to call these at the start and end of your Macro1. You might also want to add an Application.ScreenUpdating = False at the start to avoid flicker as it loops through all the worksheets and then Application.ScreenUpdating = True at the end of Macro1.

    0 讨论(0)
提交回复
热议问题