How to code in VBA for requesting password when clicked on a button?

3.4k Views Asked by At

I have got a command button on one of the excel sheet to hide/unhide one of the worksheet. See below code.

However, now I want to add a capability for the admin to enter the password in order to unhide the sheet, else anyone can click the button and unhide the data sheet.

Is there a way to force excel to show the normal enter password prompt to unhide?

Thanks

Sub myButton()

ActiveWorkbook.Unprotect

If (Sheets("Sheet2").Visible) Then 
    Sheets("Sheet2").Visible = False 
    Sheets("Sheet1").Select          
Else
    Sheets("Sheet2").Visible = True  
    Sheets("Sheet2").Select          
End If

ActiveWorkbook.Protect Password:="password", structure:=True, Windows:=False

End Sub
2

There are 2 best solutions below

2
On

You can use an inputbox to collect input from a user. Not exactly sure what you are trying to do, but maybe something like this works.

Option Explicit
Sub myButton()

    Dim pword As String

    pword = InputBox("Please enter a password", "Password Entry")

    If (Len(Trim$(pword)) = 0) Then Exit Sub

    ActiveWorkbook.Unprotect pword

    If (Sheets("Sheet2").Visible) Then
        Sheets("Sheet2").Visible = False
        Sheets("Sheet1").Select
    Else
        Sheets("Sheet2").Visible = True
        Sheets("Sheet2").Select
    End If

    ActiveWorkbook.Protect Password:=pword, structure:=True, Windows:=False

End Sub
0
On

I was able to resolve this with few tweaks. Thanks Ryan for your help!

Sub myButton()

Dim pword As String

If (Sheets("Sheet2").Visible) Then
    Sheets("Sheet2").Visible = False
    Sheets("Sheet1").Select
Else

pword = InputBox("Please enter a password", "Password Entry")

If pword = "password" Then

ActiveWorkbook.Unprotect "password"

    Sheets("Sheet2").Visible = True
    Sheets("Sheet2").Select

ActiveWorkbook.Protect Password:="password", structure:=True, Windows:=False

Else
    MsgBox ("Wrong Password")
End If
End If

End Sub