Vba worksheet protection in vba in Excel
Like the Workbook protection, worksheet too can be protected to deny any changes to the whole or some part of the sheet.
For example, if a company wants an excel sheet to be filled by employees, without modifying the existing data, then the sheet and the cells can be protected.
In this way, the user will be able to modify only certain section of the worksheet.
It is to be noted that, Worksheet level protection is not intended as a security feature.
It simply prevents users from modifying locked cells within the worksheet.
The following code shows how to protect unprotect worksheet using VBA.
For demonstration, this sheet has been chosen to protect and redo.
- Sub protect_sheet()
- Dim pwd As String
- Dim prsht As Worksheet
- Set prsht = Sheets("Q99")
- pwd = InputBox("Please enter a password to protect this sheet")
- prsht.Protect pwd, True, True
- MsgBox "This sheet is password protected"
- End Sub
Note that, following the execution of this code, the sheet will be protected with given password.
The password is shown in the Cell S1 for the ease of the user.
Once tested, unprotect the sheet by Right clicking on this tab as shown below.
In the window that appears, enter the password.
The screenshot of the editor is as shown below.