Home » excel » Excel VBA password protect a command button

Excel VBA password protect a command button

Posted by: admin May 14, 2020 Leave a comment

Questions:

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!

How to&Answers:

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

Answer:

Use a static string var within the CommandButton1_Click sub procedure. 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