简体   繁体   English

Excel VBA密码保护命令按钮

[英]Excel VBA password protect a command button

I've got a very large and somewhat fragile spreadsheet that I'm working on, and I'd like to limit access to more complicated macros--ones that delete or add data. 我正在处理一个非常大且有些脆弱的电子表格,我想限制对更复杂的宏(删除或添加数据的宏)的访问。 I'm less worried about security than I am about someone who doesn't know what they're doing deleting unfortunate things. 我对安全性的担心比对不知道他们在删除不幸的事情的人所担心的要少。 I've used the 'inputbox' password trick, but it becomes slightly annoying to have to keep putting in the password over and over. 我已经使用了“输入框”密码技巧,但是必须不断重复输入密码,这有点烦人。 Is there any way to have the macro 'remember' that I put in the password once, and then reset after I close the sheet, without storing it in a cell somewhere? 有什么方法可以让宏“记住”一次我输入密码,然后在关闭工作表后将其重置,而不将其存储在某个位置的单元格中吗?

Here's the code I'm currently using: 这是我当前正在使用的代码:

Sub ControlPanel()

Dim PassProtect As Variant

PassProtect = InputBox(Prompt:="Please enter the password to unlock the updater." & vbCrLf & "(Case Sensitive)", Title:="Control Panel")

  If PassProtect = vbNullString Then Exit Sub

If PassProtect = "password" Then
    ControlPanelForm.Show vbModeless    
Else: MsgBox Prompt:="Incorrect password. Please try again.", Buttons:=vbOKOnly
End If

End Sub

Thanks! 谢谢!

Use a static string var within the CommandButton1_Click sub procedure. 在CommandButton1_Click子过程中使用静态字符串var。 Once entered correctly, it will be 'remembered' for the duration of the session. 一旦正确输入,它将在会话期间被“记住”。

Option Explicit

Private Sub CommandButton1_Click()
    Static pwd As String

try_again:
    If pwd <> "thePassword" Then
        'password challenge
        pwd = InputBox(Prompt:="Please enter the password to unlock the updater." & vbLf & "(Case Sensitive)", _
                       Title:="Control Panel")

        'check if the password challenge was cancelled
        If pwd = vbNullString Then Exit Sub

        'compare again
        GoTo try_again
    End If

    'all the good code once the password challenge has been passed
    Debug.Print "pass"

End Sub

You can use a public variable to store a value when the workbook is open, so the code would become: 打开工作簿时,可以使用公共变量来存储值,因此代码将变为:

Public pblnEnteredPassword As Boolean

Sub ControlPanel()

    Dim PassProtect As Variant

    If pblnEnteredPassword Then GoTo DoStuff

    PassProtect = InputBox(Prompt:="Please enter the password to unlock the updater." & vbCrLf & "(Case Sensitive)", Title:="Control Panel")

      If PassProtect = vbNullString Then Exit Sub

    If PassProtect = "password" Then
        pblnEnteredPassword = True
        GoTo DoStuff
    Else
        MsgBox Prompt:="Incorrect password. Please try again.", Buttons:=vbOKOnly
        Exit Sub
    End If

DoStuff:
    ControlPanelForm.Show vbModeless

End Sub

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

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