Protecting Specific Worksheets in an Excel Workbook using VBA
Microsoft VBA question
I have 5 worksheets in my workbook. I wish to password protect the sheets four and five when the workbook is opened. That is, the sheets 4 and 5 are
not visible to somebody who doesn’t have a password. How can I implement this? Thanks for your help in advance!
Andrea from Goa wants to do the following:
•Create a user-form that loads when the workbook is opened
•The user is required to enter a password in a textbox
•The password should not be visible during entry (obviously!)
•On clicking on the login command button the password is authenticated and the user can see all the worksheets
•In case the password entered is incorrect the user has an opportunity to retry.
•If she doesn’t want to retry or doesn’t have a password, she can select ‘no’ and proceed to open the workbook without the protected worksheets.
How to implement the process step by step:
1.Click on the developer tab
2.Select ‘Visual Basic’
3.Double-click on the item ‘this workbook’ on the left-side of the window
4.Enter the code below by selecting ‘workbook’ in the right-hand side window under ‘General’ and under declarations select ‘Open’. Also select ‘workbook’ under ‘General’ and ‘Before close’ under ‘Declarations’ and write the relevant code as shown below.
VBA coding when the user form loads
Private Sub Workbook_Open()
Private Sub Workbook_BeforeClose(Cancel As Boolean)
Sheets(“Sheet4”).Visible = False
Sheets(“Sheet5”).Visible = False
Next click on the ‘insert’ menu, select ‘userform’ and on the form create your controls using standard methods to provide a label (enter password), a textbox and a command button (login). Then write code for the command button as shown below:
VBA code for the command button:
Private Sub CommandButton1_Click()
If Me.TextBox1.Value = “azby,,1029” Then (How to hide this VBA code – video)
Sheets(“Sheet4”).Visible = True
Sheets(“Sheet5”).Visible = True
Retry = MsgBox(“The password is incorrect. Do you wish to try again?”, vbYesNo, “Retry?”)
Select Case Retry
Case Is = vbYes
Me.TextBox1.Value = “”
Case Is = vbNo
Watch the video below to see how the complete process can be implemented easily: