QP School

Full Version: Protect and unprotect worksheet with VBA
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
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.