繁体   English   中英

Excel VBA密码保护命令按钮

[英]Excel VBA password protect a command button

我正在处理一个非常大且有些脆弱的电子表格,我想限制对更复杂的宏(删除或添加数据的宏)的访问。 我对安全性的担心比对不知道他们在删除不幸的事情的人所担心的要少。 我已经使用了“输入框”密码技巧,但是必须不断重复输入密码,这有点烦人。 有什么方法可以让宏“记住”一次我输入密码,然后在关闭工作表后将其重置,而不将其存储在某个位置的单元格中吗?

这是我当前正在使用的代码:

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

谢谢!

在CommandButton1_Click子过程中使用静态字符串var。 一旦正确输入,它将在会话期间被“记住”。

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

打开工作簿时,可以使用公共变量来存储值,因此代码将变为:

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