I recently had a client who has a requirement to protect and unprotect a lot of sheets. This was something they didn’t do very often, but when they did, they described the process of doing it manually as cumbersome.
I’m sure that once you get more than a few sheets, protecting and unprotecting each one by hand does indeed become a chore.
So I wrote a couple of macros that does the job for you. One macro protects all the sheets in a workbook, the other unprotects them all.
I just use a For ... Next loop to go through each sheet in turn. Then I use either the Protect or Unprotect method on each worksheet object.
For Each WSheet In Worksheets WSheet.Protect Password:=Pwd Next WSheet
The password that is stored in the string variable Pwd is input by the user. So the password isn't stored in the VBA code itself, making it secure and therefore allowing you to distribute the workbook with the VBA included if you wish.
In order to get the password, the code uses an InputBox to ask the user to enter it before protecting/unprotecting sheets.
Pwd = InputBox("Enter the password to protect all worksheets", "Enter Password")
If a blank password is entered the code displays a message saying this and then exits the macro without doing anything.
How to Use The Code
As this is something that you can use on multiple workbooks, I'd create a Personal.xlsb (if you don't already have one), and copy/paste the code in there.
You can then either create an icon on your Quick Access Toolbar, or modify your Ribbon to make the macros available.
What's Protected?
By default everything on the sheet is protected which includes things like shapes, charts and macros. The insertion/deletion of rows and columns is not allowed, neither are formatting changes.
Sorting, filtering and the use of pivot tables are also not allowed on a protected sheet. As you may want your users to be able to do these things, you can alter the macro to allow this.
To do this we specify the relevant parameters for the Protect method like this:
WSheet.Protect Password:=Pwd, AllowSorting:=True, AllowFiltering:=True, AllowUsingPivotTables:=True
The default values for AllowSorting, AllowFiltering and AllowUsingPivotTables are False, so we don't need to explicitly specify them if we want to pevent these particular actions.
Follow this link to check the MSDN reference for the Worksheet.Protect method
Password Protected Ranges
If you have protected all sheets, and also have ranges protected with different passwords, your users can still edit these ranges by entering the correct password(s) for those ranges.
Read this article to see how to protect different ranges with different passwords.
Leave a Comment or Please Share This
I'd love to hear your feedback on this code (or your tips for the World Cup), so please leave a comment here.
The Code
Enter your email address below to download the sample workbook.
Option Explicit Sub ProtectAllSheets() ' Written by Philip Treacy ' My Online Training Hub https://www.myonlinetraininghub.com/protect-and-unprotect-all-sheets-in-a-workbook ' June 2014 Dim WSheet As Worksheet Dim Pwd As String Application.ScreenUpdating = False Pwd = InputBox("Enter the password to protect all worksheets", "Enter Password") If Pwd = vbNullString Then NoPassword End If For Each WSheet In Worksheets WSheet.Protect Password:=Pwd Next WSheet Application.ScreenUpdating = True End Sub Sub UnProtectAllSheets() ' Written by Philip Treacy ' My Online Training Hub https://www.myonlinetraininghub.com/protect-and-unprotect-all-sheets-in-a-workbook ' June 2014 Dim WSheet As Worksheet Dim Pwd As String Application.ScreenUpdating = False Pwd = InputBox("Enter the password to unprotect all worksheets", "Enter Password") If Pwd = vbNullString Then NoPassword End If On Error Resume Next For Each WSheet In Worksheets WSheet.Unprotect Password:=Pwd Next WSheet If Err <> 0 Then MsgBox "The password you entered is incorrect. All worksheets are still protected.", vbCritical, "Incorrect Password" End If On Error GoTo 0 Application.ScreenUpdating = True End Sub Sub NoPassword() MsgBox "You didn't enter a password. This macro will not continue.", vbCritical + vbOKOnly, "No password entered." Application.ScreenUpdating = True End End Sub
Paul
hello
Trying to adapt this code to also set userinterfaceonly:=True on password locked sheets but when i change to this below i get a runtime error??
Also when i use the code without user interface it does lock and unlock all sheets but the unlock code returns the error that the sheets are not protected ( even though they are )
head scratching
Option Explicit
Sub ProtectAllSheets()
‘ Written by Philip Treacy
‘ My Online Training Hub https://www.myonlinetraininghub.com/protect-and-unprotect-all-sheets-in-a-workbook
‘ June 2014
Dim WSheet As Worksheet
Dim Pwd As String
Application.ScreenUpdating = False
Pwd = InputBox(“Enter the password to protect all worksheets”, “Enter Password”)
If Pwd = vbNullString Then
NoPassword
End If
For Each WSheet In Worksheets
WSheet.Protect Password:=Pwd, UserInterfaceOnly:= True
Next WSheet
Application.ScreenUpdating = True
End Sub
Philip Treacy
Hi Paul,
Using your code I’m not getting any errors.
Can you please start a topic on our forum and attach your file so we can take a look.
regards
Phil
Biplab Das
Specific Range in all sheets how to protect.
Catalin Bombea
Hi,
You can try this:
Sub LockCells()
Dim Wks as Worksheet
For each Wks in ThisWorkbook.Worksheets
Range("A1:C15, A40:D45").Locked = False
Wks.Protect password:="password", UserInterfaceOnly:=True
Next Wks
End Sub
Deepak
Sub Sign()
‘
‘ TM_(“UserName”)
‘
‘
‘
‘ActiveCell = Environ(“UserName”)
If ActiveCell = “” Then
Sheet1.Unprotect Password:=”bangalore”
ActiveCell = Application.UserName
Selection.Locked = True
Selection.FormulaHidden = False
Sheet1.Protect Password:=”bangalore”
Else
MsgBox “Cell Value should be blank”
End If
End Sub
Hello Juan,
can you help me/Correct on above coding with the changes to protect all Sheets instead of Sheet1?
Catalin Bombea
Hi Deepak,
You can adapt these codes: protect-and-unprotect-all-sheets-in-a-workbook
Catalin
jue
Hi. I would like to know how to protect “shared excel file”. Only certain user is allow to edit all range in excel meanwhile the rest people can edit certain range in that file. Beside that, this file also have grouping for each category which is only that allowed user can group or ungroup that category. Hope somebody can help. Please ask if my explanation is not clear enough.
Catalin Bombea
Hi Jue,
You can take a look at this tutorial.
Let me know if this is what you was looking for.
Catalin
peter
you have coded: –
Application.ScreenUpdating = False
and later (at the exit of the procedure): –
Application.screenUpdating = True
This may override the previous setting of ScreenUpdating, so it would be better to revert to the previous condition. Try: –
dim asu
asu = Application.screenUpdating
Application.ScreenUpdating = False
and later: –
Application.ScreenUpdating = asu ‘(to restore the previous condition)
Philip Treacy
Hi Peter,
You make a valid point. I guess when coding something like this you are looking to run the code on its own. I’m not calling it from another routine where I may want to restore Application.ScreenUpdating to its previous value.
Good point though.
Phil
Jef
This concept is interesting and I’ve been using variants of it. Thanks for sharing.
Philip Treacy
No worries Jef 🙂
Sumit Bansal
Thanks Phillip.. this can save a lot of time.
As for world cup, I am with Conor 🙂
Philip Treacy
You’re welcome Sumit. Yes I think Argentina will be hard to beat.
KV
Hi Philip, I’m not much of a football fan (cricket is my thing), but I can understand your passion for it 🙂
Just a quick question – you mentioned “If you have protected all sheets, and also have ranges protected with different passwords, your users can still edit these ranges by entering the correct password(s) for those ranges.”
Is this a new feature in Excel 2013 ?
I don’t know if there such a thing in Excel 2010 or prior.
Philip Treacy
Hi KV,
I like playing cricket, it’s good fun with the kids.
Since at least Excel 2002 you can protect ranges with passwords. From 2002 onwards you can even have different passwords for different ranges.
Have a look at this article to read how to do it
Protecting Ranges With Passwords
Regards
Phil
KV
Thanks Phil … This is a new one for me, and is going to be very useful !
All along I used to format specific cells or ranges as unlocked, and then protect the sheet to prevent unintended changes.
Now this feature will help me to allow data entry only to a select group of users, without bothering with the locked / unlocked cell formatting.
Philip Treacy
No worries 🙂
Glad to be able to make life that little bit easier
Juan Aguero
Thank you very much for this fantastic tip, Phillip. I have a question: does the Excel expert advanced cover introduction to macros?
Regarding the World Cup, I think that a team from South America will finish with the World Cup.
It was the first time after many years that my country Paraguay is not present in the event. It would have been fantastic to support the team personally, as Brazil is a neighboring country.
Philip Treacy
Thanks Juan.
No the Excel Expert course doesn’t have an into to macros. We have a course in development though.
I can empathise with you Juan, Ireland are not in Brazil either 🙁
Juan Aguero
What a great news, I’ll wait for the macro intro course with emotion!:) Now that Paypal finally arrived to Paraguay, it’d me much easier to purchase your courses.
Hope our teams be lucky in the next World Cup! I support any team from South America: Argentina, Brazil, Chile (that largely surprised all of us), Colombia, Uruguay. In sum, anyone will represent this part of the world with dignity 🙂 The matches are being shown on TV at very convenient hours, beginning at 12 pm and finishing with the last game of the day at 6 pm until 8 pm.
Mynda Treacy
Yes Chile are playing very well.
Its nice that the games are on at good times for you. Not having to get up at 2am like we are!
Maxime Manuel
I laughed a lot at your introduction about the World Cup. You are so hilarious. LOL.
This is good time saver. We all face situation where we need to lock then unlock multiple sheets.
Many thanks for sharing.
Philip Treacy
I really want to be a comedian 🙂
Thanks Maxime, glad that you find this useful.
Jeanette Underwood
I am getting “Compile error: Named argument not found” on the following:
AllowEditObjects:=True
I have it where your example showed AllowSorting:=True – is this not an option?
Thank you!
Philip Treacy
Hi Jeanette,
AllowEditObjects isn’t a valid paramter for the .Protect method.
You can check what is valid here
MSDN Worksheet.Protect Method
What is it you are trying to allow ? Editing of shapes?
Regards
Phil
Jeanette Underwood
I have a set of templates I send out monthly for updating from numerous large teams scattered across the globe. I have all of the sheets locked but when I prep the files for updating, I put boxes over the parts they are supposed to update, which they delete (which tells me they are done editing). When I protect the sheets, I have to scroll down and put a check box in the “Edit Objects” option to allow them to delete the boxes. In looking at the list you linked to in your reply, I’m guessing maybe I need DrawingObjects but I’m not sure how to write the expression since true seems to indicate locked at this link.
Jeanette Underwood
I should add that the reason I am keen to use this macro is that I frequently forget to scroll down and put the check box in Edit Objects, which leads to all kinds of frustration as we have 5 distinct files, each with 8-10 worksheets.
Jeanette Underwood
I figured it out – thank you! The code is DrawingObjects=False.
Catalin Bombea
Hi Jeanette,
The most simple way to get the syntax of all parameters from Protect Sheet procedure, is to start the macro recorder, then manually open the Protect menu and check all boxes, confirm password and click ok. Stop the recorder, click Alt+F11 and you can see the code recorded. This way, you can never make mistakes 🙂 (if the recorder works fine 🙂 )
Here is what recorder shows:
Catalin
Catalin Bombea
You may also consider The UserInterfaceOnly option, which allows you to run code without unprotecting the sheet.
Note that this setting is not saved when you close the workbook, so you need to set it when the workbook is opened. The best place to do this is in the Workbook_Open event procedure. For example,
Private Sub Workbook_Open()
Sheets(“Sheet1”).Protect UserInterfaceOnly:=True
End Sub
Another source of information is Excel help files, here is what help file says:
Worksheet.Protect Method (Excel)
Protects a worksheet so that it cannot be modified.
Syntax
expression.Protect(Password, DrawingObjects, Contents, Scenarios, UserInterfaceOnly, AllowFormattingCells, AllowFormattingColumns, AllowFormattingRows, AllowInsertingColumns, AllowInsertingRows, AllowInsertingHyperlinks, AllowDeletingColumns, AllowDeletingRows, AllowSorting, AllowFiltering, AllowUsingPivotTables)
UserInterfaceOnly Description: True to protect the user interface, but not macros. If this argument is omitted, protection applies both to macros and to the user interface.
Catalin Bombea
Mynda Treacy
Hi Jeannette,
Can you send me some of these files to look at via the Helpdesk please?
Regards
Phil
Jeanette Underwood
Phil – thanks, but I did figure it out. Nice code, btw. A real timesaver! Thanks!
Philip Treacy
You’re welcome Jeanette. Glad you got it figured out.
Phil
Jeanette Underwood
I do have one more question. I shared your macro at our PMO staff meeting yesterday and everyone loved it. I use the little lock and key icons on the QAT to access them and it works great. But someone asked if there is a way to mask the password input and I know you can’t do that with an input box. Is there another way to have it mask the password?
Catalin Bombea
Hi Jeanette,
The easiest way to mask a password is to use a simple userform with a textbox, (you can set the property: PasswordChar to any character from keyboard, that char will be seen instead of the typed characters), instead of using an Application.InputBox, you are right, this input box is not hiding the characters.
You can test this simple form from our OneDrive folder.
Catalin
Andrew Evans
This is exactly what I have done for one of my workbooks – one of the allows that I have though is to edit objects, otherwise you cannot add comments to cells which is something I find useful. I also only allow users to select unlocked cells.
As for the football – I think Australia played well and were unlucky to lose, and Tim Cahill’s goal could easily be on the shortlist for goal of the tournament.
Philip Treacy
Thanks Andrew.
Yes that goal was extra-ordinary. I nearly knocked the laptop off the desk when I jumped up shouting 🙂
Jeanette Underwood
Andrew – can you tell me the code to allow editing of objects? i am getting a compile error. Thanks!
Maria
Hello Mynda,
thanks to share this … I am still hesitant to protect sheets … I always fear that they are protected from myself also. 🙂 I’ll try with this.
For the World Cup: my husband thinks of a Bresil – Italy final! 😉 So Conor is not so wrong following his stomach!
I am supportive of my country, Germany, but I don’t think that they will make it to the final. Maybe my adopted country France will make it a little farther … they at least improved their attitude.
Kind regards
Philip Treacy
Hi Maria,
As long as you don’t forget the password you’ll be alright 🙂
Germany looked very good against Portugal, they should go a long way in this tournament.
Phil
Peter Richardson
Thanks for sharing this VBA code.
Argentina to win World Cup, although both Mexico and Chile have looked good. No doubt Germany will also be in the mix. Spain never really got started.
Pete
Philip Treacy
No worries Peter 🙂
Argentina are my bet too, and yes Germany always do well in tournaments.
Watch out for Belgium, they have an incredible array of young talent.
ahmed
Many many thanks for sharing such useful information.
Philip Treacy
You’re welcome Ahmed
DNYANDEO
Hi,
Many many thanks for sharing such useful information. It works.
Philip Treacy
Glad to help 🙂
Binh Ngo
A fantastic idea. This code makes it much simpler to protect important works/documents.
Philip Treacy
Thanks Binh 🙂
randeep bhatia
Hi Mynda I have a query.
I need a macro that would be in my personal xlsb which on running gives me pop to check box with the sheet names in that workbook . when i tick those check boxes it should hide the sheets and remaining should be visible. The condition is that the sheets should be very hidden.
The macro should be able to work on any workbook that i open by calculating the sheets in that workbook and giving all sheetnames in that checkbox popup.
Thanks
Randeep
Philip Treacy
Hi Randeep,
I’ve replied to you by email.
Regards
Phil