Sub TestProtection()
Dim ws As Worksheet
Set ws = ThisWorkbook.Worksheets(1)
If Not ProtectWorksheet(ws, "TestPassword") Then
Debug.Print "The worksheet could not be protected."
Else
Debug.Print "The worksheet has been protected."
End If
If UnprotectWorksheet(ws, "TestPassword") Then
Debug.Print "The worksheet has been unprotected."
Else
Debug.Print "The worksheet could not be unprotected."
End If
Set ws = Nothing
End Sub
Function ProtectWorksheet(ws As Worksheet, sPassword As String) As Boolean
On Error GoTo ErrHandler
If Not ws.ProtectContents Then
ws.Protect sPassword, True, True, True
End If
ProtectWorksheet = True
Exit Function
ErrHandler:
ProtectWorksheet = False
End Function
Function UnprotectWorksheet(ws As Worksheet, sPassword As String) As Boolean
On Error GoTo ErrHandler
If ws.ProtectContents Then
ws.Unprotect sPassword
End If
UnprotectWorksheet = True
Exit Function
ErrHandler:
UnprotectWorksheet = False
End Function