簡體   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