简体   繁体   中英

Excel Run Macro button with password protection

My workbook is passwordprotected and consists of unlocked cells for input and ane button for PDF print. Due to the password protection of the sheets the PDF print button doesn't work.

I have tried with the following earlier questions and answers. Yet it says that my entered password is wrong(!)

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

Sub ButtonClick()

UnprotectAll

'Some stuff here

ProtectAll

End Sub

Private Const yourPassword As String = "ThePassWord"

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

I get the

error "1004".
The password you supplied is not correct.

  1. Make sure you use Option Explicit as first line in every module and worksheet code! This ensures you don't run into a not declared local scope variable yourPassword which then is empty.

    I recommend always to activate Option Explicit : In the VBA editor go to ToolsOptionsRequire Variable Declaration .

  2. Make sure you unprotect (manually) all your sheets using your password.

  3. Define your new desired password as constant in a module

     Private Const yourPassword As String = "ThePassWord" 
  4. Use this constant for your .Protect / .Unprotect

     sh.Protect Password:=yourPassword 
  5. Then run your code again.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM