QP School
Protect and unprotect worksheet with VBA - Printable Version

+- QP School (https://qomplainerzschool.lima-city.de)
+-- Forum: Tutorials (https://qomplainerzschool.lima-city.de/forumdisplay.php?fid=3)
+--- Forum: Excel VBA Tutorials (https://qomplainerzschool.lima-city.de/forumdisplay.php?fid=48)
+--- Thread: Protect and unprotect worksheet with VBA (/showthread.php?tid=5249)



Protect and unprotect worksheet with VBA - Qomplainerz - 07-27-2023

Example:

Sub ProtectUnprotectWorksheet()
    Dim ws As Worksheet
    Dim password As String

    'Set the password for protection
    password = "mypassword"

    'Get the reference to the active worksheet
    Set ws = ActiveSheet

    'Protect the worksheet with password
    ws.Protect Password:=password

    'Wait for 2 seconds
    Application.Wait (Now + TimeValue("00:00:02"))

    'Unprotect the worksheet with password
    ws.Unprotect Password:=password
End Sub

Explanation:

The code defines a subroutine named ProtectUnprotectWorksheet.
It declares a variable ws of type Worksheet and a variable password to store the password used for protection.
The password "mypassword" is set using the password variable.
The ActiveSheet property is used to get a reference to the currently active worksheet, which will be protected and unprotected.
The Protect method is used to protect the worksheet with the specified password.
The Application.Wait function is used to introduce a delay of 2 seconds before unprotecting the worksheet. This allows time to observe the protected state.
Finally, the Unprotect method is used to unprotect the worksheet with the same password.