Protecting Worksheet Assets with the Protect Method : Worksheet Protection « Excel « VBA / Excel / Access / Word






Protecting Worksheet Assets with the Protect Method

 
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 

 








Related examples in the same category

1.Add protection to Worksheet
2.Protect Sheet
3.Unprotect worksheet
4.Show Protection Properties
5.remove user
6.Remove user edit range
7.Add user edit range
8.Formulas Protection