Macro to protect and Unprotect a worksheet

pincivma

Board Regular
Joined
Dec 12, 2004
Messages
203
Hi there

I have this code to protect and un-protect a worksheet

ActiveSheet.Unprotect Password = "test"
Code goes here
.
.
.
ActiveSheet.Protect Password = "test"

End Sub

Here is the problem. When I run the code, it runs just fine. But when I manually try to un-protect the worksheet I get the usual pop up to enter my password. When I enter my password "test" without the quotes I get a pop up that says "The password you supplied is not correct......" But id did supply the correct password. So what did I do wrong??
 

Excel Facts

Do you hate GETPIVOTDATA?
Prevent GETPIVOTDATA. Select inside a PivotTable. In the Analyze tab of the ribbon, open the dropown next to Options and turn it off
Your code does not work since my macro gets a bug right on the line
ActiveSheet.Protect Password:="test"

My code does not generate a bug and my macro runs just fine. So back to square 1
 
Upvote 0
The following code has been tested to work with Excel 2010 and 2013:
Code:
Sub Test()
    If ActiveSheet.ProtectContents Then
        ActiveSheet.Unprotect Password:="test"
        MsgBox "Sheet unprotected (Password: test)"
    End If
    If Not ActiveSheet.ProtectContents Then
        ActiveSheet.Protect Password:="test"
        MsgBox "Sheet protected (Password: test)"
    End If
End Sub
 
Upvote 0
Thanks
I will give that a try sometime tomorrow and get back to you to see if it worked or not
 
Upvote 0

Forum statistics

Threads
1,214,821
Messages
6,121,755
Members
449,049
Latest member
excelknuckles

We've detected that you are using an adblocker.

We have a great community of people providing Excel help here, but the hosting costs are enormous. You can help keep this site running by allowing ads on MrExcel.com.
Allow Ads at MrExcel

Which adblocker are you using?

Disable AdBlock

Follow these easy steps to disable AdBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the icon in the browser’s toolbar.
2)Click on the "Pause on this site" option.
Go back

Disable AdBlock Plus

Follow these easy steps to disable AdBlock Plus

1)Click on the icon in the browser’s toolbar.
2)Click on the toggle to disable it for "mrexcel.com".
Go back

Disable uBlock Origin

Follow these easy steps to disable uBlock Origin

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back

Disable uBlock

Follow these easy steps to disable uBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back
Back
Top