In this Article
- VBA Workbook Protection
- UnProtect Workbook VBA
- UnProtect Workbook With Password
- UnProtect ThisWorkbook
- UnProtect ActiveWorkbook
- UnProtect All Open Workbooks
- UnProtect Workbook – Without Knowing Password
- UnProtect All Sheets in Workbook
- Protect Workbook
- Protect Workbook No Password
- Protect Workbook With Password
- Password Protect Excel File
- Protect / UnProtect Workbook Examples
- Unhide All Worksheets in Protected Workbook
- Protect Workbook and All Sheets
Excel allows you the ability to protect your Excel workbooks from changes. This tutorial will show you how to protect or unprotect workbook structure using VBA.
VBA Workbook Protection
VBA Workbook Protection allows you to lock the structure of the workbook. When a workbook is protected, users will be unable to add, delete, hide / unhide, or protect / unprotect worksheets. If you are building a model, you probably want to turn on workbook protection to prevent users (or you!) from accidentally deleting worksheets.
UnProtect Workbook VBA
To unprotect a workbook simply use the following line of code:
Workbooks("Book1").Unprotect
Note: this code will only work if the workbook was protected without a password. If it was protected with a password, you must also enter in the password to unprotect it:
UnProtect Workbook With Password
This line of code will unprotect a workbook that has been protected with a password:
Workbooks("Book1").Unprotect Password:="password"
or you can ommit Password:=
Workbooks("Book1").Unprotect "password"
UnProtect ThisWorkbook
This code will unprotect ThisWorkbook (ThisWorkbook is the workbook where the running code is stored. It will never change).
ThisWorkbook.Unprotect
or unprotect ThisWorkbook with a password:
ThisWorkbook.Unprotect "password"
UnProtect ActiveWorkbook
This code will unprotect the ActiveWorbook.
ActiveWorkbook.Unprotect
or unprotect the ActiveWorkbook with a password:
ActiveWorkbook.Unprotect "password"
UnProtect All Open Workbooks
This code will unprotect all open workbooks:
Sub UnprotectAllOpenWorkbooks()
Dim wb As Workbook
For Each wb In Workbooks
wb.Unprotect
Next wb
End Sub
VBA Coding Made Easy
Stop searching for VBA code online. Learn more about AutoMacro — A VBA Code Builder that allows beginners to code procedures from scratch with minimal coding knowledge and with many time-saving features for all users!
Learn More
UnProtect Workbook – Without Knowing Password
If you need to unprotect a workbook without knowing the password, there are several add-ins to help. I would recommend Ribbon Commander.
UnProtect All Sheets in Workbook
After unprotecting a workbook, you might also want to unprotect all sheets in the workbook. Here’s a procedure that will unprotect all sheets:
Sub UnProtectWorkbookAndAllSheets()
Dim ws As Worksheet
ActiveWorkbook.Unprotect
For Each ws In Worksheets
ws.Unprotect
Next
End Sub
Protect Workbook
You can protect workbook structures in the same way as you unprotect.
VBA Programming | Code Generator does work for you!
Protect Workbook No Password
This line of code will protect a workbook (no password)
Workbooks("Book1").Protect
Note: I’ll often apply workbook protection without passwords, simply to prevent accidental changes to workbooks.
Protect Workbook With Password
This code will protect the workbook structure (with a password)
Workbooks("Book1").Protect "password"
or:
Workbooks("Book1").Protect Password:="password"
Password Protect Excel File
Instead of workbook protection, you might want to password-protect an entire Excel file. To do that using VBA, Save As the workbook with a password:
Workbooks("Book1").SaveAs "password"
Protect / UnProtect Workbook Examples
Unhide All Worksheets in Protected Workbook
This procedure will unprotect a workbook, hide all worksheets, and re-protect the workbook
Sub UnprotectWB_Unhide_All_Sheets()
Dim ws As Worksheet
ActiveWorkbook.Unprotect
For Each ws In Worksheets
ws.Visible = xlSheetVisible
Next
ActiveWorkbook.Protect
End Sub
Protect Workbook and All Sheets
This procedure will protect all worksheets in a workbook and then protect the workbook:
Sub ProtectWB_Protect_All_Sheets()
Dim ws As Worksheet
ActiveWorkbook.Unprotect
For Each ws In Worksheets
ws.Protect
Next
ActiveWorkbook.Protect
End Sub
You can add password protection as well:
Sub ProtectWB_Protect_All_Sheets_Pswrd()
Dim ws As Worksheet
ActiveWorkbook.Unprotect "password"
For Each ws In Worksheets
ws.Protect "password"
Next
ActiveWorkbook.Protect "password"
End Sub
To protect a workbook, you need to use VBA’s PROTECT method. By using this method, you can use a password, or even you can activate workbook protection without a password. But there’s one thing that you need to take care of the password that you use is a CASE-SENSITIVE.
Workbook.Protect "Password"
- Specify the workbook that you want to protect.
- Type and dot and select the protect method from the list or you can type “Protect”.
- Enter the password that you want to set.
- Run the code to protect the workbook.
In this tutorial, we will learn this method in different ways and we will also learn to unprotect a workbook.
Helpful Links: Run a Macro – Macro Recorder – Visual Basic Editor – Personal Macro Workbook
Protect a Workbook with Password
Below is the code that you need to use to protect a workbook with a password. In this code, you have the workbook name first and the protection method with the password.
Workbooks("Book1").Protect "test123"
And when I run this code, it locks the “Book1” workbook.
Protect a Workbook without a Password
And if you want to protect a workbook without a password you need to skip the “Password” argument, just like the following code.
Workbooks("Book1").Protect
If you are trying to protect a workbook without a password that is already protected with a password Excel will show a dialogue box to enter that password.
Unprotect a Workbook with a Password
In the same way, you can use the unprotect method to unprotect the workbook and the code for this would be like something below.
Workbooks("Book1").Unprotect "test123"
There’s one thing that you need to take care of that if you are trying to unprotect a workbook that is w
Unprotect a Workbook without a Password
And if a workbook is protected without a password you can use the same method without specifying the password argument.
Protect All the Open Workbooks
In the code below, we have FOR EACH loop to loop through all the open workbooks and protect each workbook one by one using the same protect method.
'variable to use as a workbook
Dim wb As Workbook
'loop through all the open workbooks
For Each wb In Application.Workbooks
'condition to check workbook name
If wb.Name <> "PERSONAL.XLSB" Then
'protect every workbook with a password
wb.Protect "test123"
End If
Next wb
End Sub
As I use the personal macro workbook, I have used an IF THEN ELSE statement to skip if the workbook name is “personal.xlsb”. Make sure to take care of that as well.
Protect a Closed Workbook
You can also protect and unprotect a workbook that is closed and saved on a location. Look at the following code where I have used the location of my desktop to use the file “test.xlsx”.
Sub vba_protect_workbook()
'declare varibale to use for the workbook
Dim wb As Workbook
'open the workbook that you want to protect
Set wb = Workbooks.Open("C:UsersDellDesktoptest.xlsx")
'turn off the screen-updating to _
done everything in the backend
Application.ScreenUpdating = False
'protect the workbook
wb.Protect
'close the workbook after protecting
wb.Close SaveChanges = True 'turn off the screen-updating
Application.ScreenUpdating = True
End Sub
The above code used Workbook.Open the method to open the workbook that you want to protect and then disable the screen updating to work in the backend.
Protect All the Closed Workbooks from a Folder
The following code loops through all the workbooks that are there in the folder that you specified as the path. And then open each workbook, protect it, and close it one by one.
Sub vba_protect_all_the_workbooks()
'declare variables
Dim wb As Workbook
Dim myPath As String
Dim myFile As String
Dim myExtension As String
Dim FldrPicker As FileDialog
'optimize macro
Application.ScreenUpdating = False
Application.EnableEvents = False
Application.Calculation = xlCalculationManual
'specify the folder where workbooks are saved
myPath = "C:UsersDellDesktopfolder"
'jump to reset setting if there's an error
On Error GoTo ResetSettings
'target file fxtension (must include wildcard "*")
myExtension = "*.xls*"
'target path
myFile = Dir(myPath & myExtension)
'Loop through each Excel file in folder
Do While myFile <> ""
'Set variable equal to opened workbook
Set wb = Workbooks.Open(Filename:=myPath & myFile)
'protect workbook
wb.Protect
'Save and Close Workbook
wb.Close SaveChanges:=True
'Get next file name
myFile = Dir
Loop
'Message Box when task is completed
MsgBox "Done!"
'reset setting that were change for optimization
ResetSettings:
Application.EnableEvents = True
Application.Calculation = xlCalculationAutomatic
Application.ScreenUpdating = True
End Sub
More on VBA Workbooks
VBA Save Workbook | VBA Close Workbook | VBA Delete Workbook | VBA ThisWorkbook | VBA Rename Workbook | VBA Activate Workbook | VBA Combine Workbook | VBA Check IF a Workbook is Open | VBA Open Workbook | VBA Check IF an Excel Workbook Exists in a Folder| VBA Create New Workbook (Excel File)
- VBA Workbook
I agree with @Richard Morgan … what you are doing should be working, so more information may be needed.
Microsoft has some suggestions on options to protect your Excel 2003 worksheets.
Here is a little more info …
From help files (Protect Method):
expression.Protect(Password, Structure, Windows)
expression Required. An expression that returns a Workbook object.
Password Optional Variant. A string that specifies a case-sensitive password for the worksheet or workbook. If this argument is omitted, you can unprotect the worksheet or workbook without using a password. Otherwise, you must specify the password to unprotect the worksheet or workbook. If you forget the password, you cannot unprotect the worksheet or workbook. It’s a good idea to keep a list of your passwords and their corresponding document names in a safe place.
Structure Optional Variant. True to protect the structure of the workbook (the relative position of the sheets). The default value is False.
Windows Optional Variant. True to protect the workbook windows. If this argument is omitted, the windows aren’t protected.
ActiveWorkbook.Protect Password:="password", Structure:=True, Windows:=True
If you want to work at the worksheet level, I used something similar years ago when I needed to protect/unprotect:
Sub ProtectSheet()
ActiveSheet.Protect "password", True, True
End Sub
Sub UnProtectSheet()
ActiveSheet.Unprotect "password"
End Sub
Sub protectAll()
Dim myCount
Dim i
myCount = Application.Sheets.Count
Sheets(1).Select
For i = 1 To myCount
ActiveSheet.Protect "password", true, true
If i = myCount Then
End
End If
ActiveSheet.Next.Select
Next i
End Sub
Protect Method of Workbook Object VBA
When we are dealing with confidential information or data we need to Protect Workbook if you want from the user to edit data, delete data, and move data in Excel VBA. If user wants to see data in workbook user should have password to view data in the workbook. We need to protect workbook at the end of the procedure once changes has done to the workbook using VBA. If you forgot the password, you cannot unprotect the workbook.
- Why we need to Protect a Workbook using VBA?
- VBA Protect Workbook – Syntax
- VBA Protect Workbook: Example 1
- VBA Protect Workbook: Example 2
- VBA Protect Workbook – Instructions
Why we need to Protect a Workbook using VBA?
When workbook has sensitive data to deal with confidential information or data we need to Protect Workbook in Excel VBA. You should protect your complete workbook then only authorized users can view or modify the data.
VBA Protect Workbook – Syntax
Here is the syntax to Protect workbook using VBA.
Workbooks(“Your Workbook Name”).Protect(
Where
Password: Its Optional argument. It specifies a case sensitive password for the workbook. If we want to protect workbook then you have to mention password argument, otherwise you can omit it. When you want to unprotect your protected workbook you must specify your password.
Structure: Its Optional parameter. The default value is False. If we mention it as True that means protect the workbook structure.
Windows: Its Optional parameter. The default value is False. If we mention it as True that means protect the workbook windows.
In the above syntax we are using ‘Protect’ method of workbook object to protect the workbook.
VBA Protect Workbook: Example 1
Please find the below example, It will show you how to protect the workbook.
Sub Protect_Sheet() Sheets("Sheet1").Protect "YourPassword", True, True End Sub
In the above example we are protecting the workbook by using ‘Protect’ method of Worksheet object in the worksheet named ‘Sheet1’. When working workbook code has password protected, if you want to do any changes in the code first you have to unprotect the password at the beginning of the procedure and at the end of the procedure you have to protect it again.
VBA Protect Workbook: Example 2
Here is the example to protect ActiveWorkbook with password.
Sub Protect_Sheet() ActiveWorkbook.Protect Password:="YourPassword", Structure:=True, Windows:=True End Sub
VBA Protect Workbook – Instructions
Please follow the below step by step instructions to execute the above mentioned VBA macros or codes:
- Open an Excel Workbook
- Press Alt+F11 to Open VBA Editor
- Insert a Module from Insert Menu
- Copy the above code for activating a range and Paste in the code window(VBA Editor)
- Save the file as macro enabled workbook
- Press ‘F5’ to run it or Keep Pressing ‘F8’ to debug the code line by line.
A Powerful & Multi-purpose Templates for project management. Now seamlessly manage your projects, tasks, meetings, presentations, teams, customers, stakeholders and time. This page describes all the amazing new features and options that come with our premium templates.
Save Up to 85% LIMITED TIME OFFER
All-in-One Pack
120+ Project Management Templates
Essential Pack
50+ Project Management Templates
Excel Pack
50+ Excel PM Templates
PowerPoint Pack
50+ Excel PM Templates
MS Word Pack
25+ Word PM Templates
Ultimate Project Management Template
Ultimate Resource Management Template
Project Portfolio Management Templates
-
-
- In this topic:
-
- Why we need to Protect a Workbook using VBA?
- VBA Protect Workbook – Syntax
- VBA Protect Workbook: Example 1
- VBA Protect Workbook: Example 2
- VBA Protect Workbook – Instructions
VBA Reference
Effortlessly
Manage Your Projects
120+ Project Management Templates
Seamlessly manage your projects with our powerful & multi-purpose templates for project management.
120+ PM Templates Includes:
One Comment
-
Chris Bille
January 13, 2019 at 6:22 PM — ReplyI have three macros on my employees time card
1. to clear the sheet
2. to save the template sheet to a new tab with the current end of work date
3. email the time card.How can I protect the workbook with structure so that the sheets cannot be deleted while still using the macros. I can currently protect only the sheet
Effectively Manage Your
Projects and Resources
ANALYSISTABS.COM provides free and premium project management tools, templates and dashboards for effectively managing the projects and analyzing the data.
We’re a crew of professionals expertise in Excel VBA, Business Analysis, Project Management. We’re Sharing our map to Project success with innovative tools, templates, tutorials and tips.
Project Management
Excel VBA
Download Free Excel 2007, 2010, 2013 Add-in for Creating Innovative Dashboards, Tools for Data Mining, Analysis, Visualization. Learn VBA for MS Excel, Word, PowerPoint, Access, Outlook to develop applications for retail, insurance, banking, finance, telecom, healthcare domains.
Page load link
3 Realtime VBA Projects
with Source Code!
Go to Top
Get our FREE VBA eBook of the 30 most useful Excel VBA macros.
Automate Excel so that you can save time and stop doing the jobs a trained monkey could do.
Claim your free eBook
In a previous VBA Code Snippet, we covered protecting and unprotecting worksheets. In this post, we will consider protecting and unprotecting workbooks. The two topics are closely related, so if this post does not provide the information you need, then read that post too.
Before getting started, there is an important change in Excel 2013 to be considered.
The difference between Single & Multiple Document Interface
In Excel 2010 and prior Excel had a Multiple Document Interface (MDI), which means multiple workbooks opened within the same Excel window. Excel 2013 introduced the Single Document Interface (SDI), where each document has its own window with its own Ribbon.
When protecting workbooks the Windows option is disabled within Excel 2013 and above.
The purpose of the Windows setting was to fix the size of the spreadsheet within the instance of Excel. However, now that each spreadsheet behaves as if a separate instance, fixing the size of the window now serves no purpose.
The code below will work for both MDI and SDI, however protecting the Workbook window will have no use in Excel 2013 and above.
Basic Protecting and Unprotecting
'Protect a workbook ThisWorkbook.Protect 'Unprotect a workbook ThisWorkbook.Unprotect
Checking if a workbook is protected
'Show message box if the Structure is Protected If ThisWorkbook.ProtectStructure = True Then MsgBox "Structure Protected" 'Show message box if the Window is Protected If ThisWorkbook.ProtectWindows = True Then MsgBox "Windows Protected" 'Show message box if both the Structure or Window are Protected If ThisWorkbook.ProtectStructure = True Or ThisWorkbook.ProtectWindows = True Then MsgBox "Windows and Structure Protected" End If
Protecting and unprotecting with a password
'Protect with a password ThisWorkbook.Protect Password:="myPassword" 'Unprotect with a password ThisWorkbook.Unprotect Password:="myPassword"
If an incorrect password is provided the following error message will show.
The code below will catch the error and provide a custom message.
'Catch the error caused by an incorrect password On Error Resume Next ThisWorkbook.Unprotect Password:="incorrectPassword" If Err.Number <> 0 Then MsgBox "The Password provided is incorrect" Exit Sub End If On Error GoTo 0
Protect the Structure or the Windows
Protecting the structure prevents users from creating, moving, deleting, hiding and unhiding worksheets. Protecting windows is described above.
'Protecting the Structure or the Windows ThisWorkbook.Protect Password:="myPassword", Structure:=True, Windows:=True
Other related VBA code snippets
The following VBA Code Snippets will be useful for applying this post in a wider context.
- Protect and unprotect worksheets
- Loop through every worksheet or every workbook
- Workbook properties and actions
- Password protect an Excel file
About the author
Hey, I’m Mark, and I run Excel Off The Grid.
My parents tell me that at the age of 7 I declared I was going to become a qualified accountant. I was either psychic or had no imagination, as that is exactly what happened. However, it wasn’t until I was 35 that my journey really began.
In 2015, I started a new job, for which I was regularly working after 10pm. As a result, I rarely saw my children during the week. So, I started searching for the secrets to automating Excel. I discovered that by building a small number of simple tools, I could combine them together in different ways to automate nearly all my regular tasks. This meant I could work less hours (and I got pay raises!). Today, I teach these techniques to other professionals in our training program so they too can spend less time at work (and more time with their children and doing the things they love).
Do you need help adapting this post to your needs?
I’m guessing the examples in this post don’t exactly match your situation. We all use Excel differently, so it’s impossible to write a post that will meet everybody’s needs. By taking the time to understand the techniques and principles in this post (and elsewhere on this site), you should be able to adapt it to your needs.
But, if you’re still struggling you should:
- Read other blogs, or watch YouTube videos on the same topic. You will benefit much more by discovering your own solutions.
- Ask the ‘Excel Ninja’ in your office. It’s amazing what things other people know.
- Ask a question in a forum like Mr Excel, or the Microsoft Answers Community. Remember, the people on these forums are generally giving their time for free. So take care to craft your question, make sure it’s clear and concise. List all the things you’ve tried, and provide screenshots, code segments and example workbooks.
- Use Excel Rescue, who are my consultancy partner. They help by providing solutions to smaller Excel problems.
What next?
Don’t go yet, there is plenty more to learn on Excel Off The Grid. Check out the latest posts: