简体   繁体   English

具有密码保护功能的Excel Run Macro按钮

[英]Excel Run Macro button with password protection

My workbook is passwordprotected and consists of unlocked cells for input and ane button for PDF print. 我的工作簿受密码保护,由用于输入的未锁定单元格和用于PDF打印的ane按钮组成。 Due to the password protection of the sheets the PDF print button doesn't work. 由于工作表的密码保护,PDF打印按钮不起作用。

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 正在运行的宏返回运行时错误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". 错误“ 1004”。
The password you supplied is not correct. 您提供的密码不正确。

  1. Make sure you use Option Explicit as first line in every module and worksheet code! 确保在每个模块和工作表代码中将Option Explicit用作第一行! This ensures you don't run into a not declared local scope variable yourPassword which then is empty. 这样可以确保您不会遇到未声明的局部范围变量yourPassword ,该变量随后为空。

    I recommend always to activate Option Explicit : In the VBA editor go to ToolsOptionsRequire Variable Declaration . 我建议始终激活Option Explicit :在VBA编辑器中,转到“ 工具” ›“ 选项” ›“ 需要变量声明”

  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 使用此常数您.Protect / .Unprotect

     sh.Protect Password:=yourPassword 
  5. Then run your code again. 然后再次运行您的代码。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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