PDA

View Full Version : [SOLVED] Help with VBA password in commanduttons



blackie42
12-14-2016, 04:34 AM
Hi,

Struggling with the following...

Create 2 buttons in sheet2 - 1 renamed Protect, 1 renamed Unprotect

Protect button will ask for password (set at "test") lock Sheet2 and hide Sheet1

Unprotect button will again ask for password (set at "test") unlockSheet2 and make Sheet1 visible.

Any help appreciated
thanks
Jon

blackie42
12-14-2016, 12:26 PM
Private Sub CommandButton1_Click()

Dim Password As String
Password = InputBox("Please enter password", "Password Required", "********")
If Password <> "Test" Then
MsgBox "Wrong Password!"
Exit Sub
Else

ActiveSheet.Protect

Sheets("Sheet2").Visible = False

End If


End Sub

Private Sub CommandButton2_Click()

Dim Password As String
Password = InputBox("Please enter password", "Password Required", "********")
If Password <> "Test" Then
MsgBox "Wrong Password!"
Exit Sub
Else

ActiveSheet.Unprotect

Sheets("Sheet2").Visible = True

End If
End Sub


This does work but allows user to unlock from ribbon without password

Kenneth Hobs
12-14-2016, 05:37 PM
Please click the # icon to insert code tags rather than quote tags for code.

That is because you did not add the password when you protected it. e.g.

Sheet2.Protect Password

I normally use ThisWorkbook's Open event to set the sheet's password with the UserInterfaceOnly option set to true. e.g.

Sheet1.Protect "ken", UserInterfaceOnly=True

blackie42
12-15-2016, 04:15 AM
Always the most obvious stuff that's missed

Thanks Ken

Will wrap the code properly in future

regards
Jon