VBA Code to Password Protect an Excel file

VBA Code Snippets

Password protecting an Excel file achieves two main objectives (1) prevents unauthorized access to the Excel file (2) prevents unauthorized modification of the Excel file.

File-level protection is not the same as worksheet protection or workbook protection.  Worksheet protection controls what a user can or cannot do on a worksheet, such as inserting rows or typing into cells.  Workbook protection prevents users from adding, deleting, moving, hiding or unhiding worksheets.

File-level protection allows for two passwords: (1) to open the file (2) to modify the file.

Save an Excel file with protection

'Save file with password required to open
ThisWorkbook.SaveAs Password:="fileOpenPassword"

'Save file to allow access, but requires password to modify
ThisWorkbook.SaveAs  writeResPassword:="modifyFilePassword"

'Save file with password required to open and modify the file
ThisWorkbook.SaveAs  Password:="fileOpenPassword", _
writeResPassword:="modifyFilePassword"

If the file already exists a confirmation message will be displayed.  For the VBA code to operate seamlessly, you will want to turn Display Alerts off before executing the code, then turning it back on after the file has been saved.

'Save file and suppress the save as warning message
Application.DisplayAlerts = False

ThisWorkbook.SaveAs Password:="fileOpenPassword", _
writeResPassword:="modifyFilePassword"

Application.DisplayAlerts = True
100 Excel VBA Macros

Do you know the fastest way to learn foreign languages?  It is to read, write, speak, and think in that language as often as possible.  Apart from speaking, programming languages are no different.  The more you immerse yourself in that language, the faster you will pick it up.

100 Excel Macros Book

Therefore, what most people like you need is lots of examples that you can practice.  That is why the 100 Excel VBA Macros eBook exists.  It’s the book for all Excel users who want to learn how to read and write Excel macros, save time, and stand out from their peers.  The book contains:

  • 100 example codes to practice reading and writing macros that will embed the language into your thinking.
  • An introduction to macros in Excel to ensure you can implement the VBA code in the book even if you have no prior knowledge.
  • Consistent code layout between examples to enable you to understand the structure and easily customize the code to meet your needs.
  • Downloadable workbook containing all the source code, so the examples can be added to your project to give you the benefit of VBA straight away.

Opening a password protected Excel file

When opening a password protected Excel file manually, the password prompts are displayed:

File Open Password
VBA File Protection - Password Protected

File Modify Password
VBA File Protection - Write Protection

Using VBA it is possible to open these files and provide the password so that the prompt does not appear.

'Open password protected file
Workbooks.Open Filename:="C:\Users\marks\Documents\PasswordProtectedFile.xlsm", _
Password:="fileOpenPassword", writeResPassword:="fileModifyPassword"

The Password and writeResPassword statements should be included or excluded depending on the file being opened.

If an incorrect password is provided the following error message will show.

Protect Workbook - Incorred Password

The code below will catch the error and provide a custom message.

'Catch an incorrect password
On Error Resume Next
Workbooks.Open Filename:="C:\Users\marks\Documents\PasswordProtecedFile.xlsm", _
Password:="fileOpenPassword", writeResPassword:="fileModifyPassword"

If Err.Number <> 0 Then
    MsgBox "The Password Provided is incorrect"
    Exit Sub
End If

On Error GoTo 0

Other related VBA code snippets

The following VBA Code Snippets will be useful for applying this post in a wider context.



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.

Email Address * First Name *

By entering your email address you agree to receive emails from Excel Off The Grid. We’ll respect your privacy and you can unsubscribe at any time.


Don’t forget:

If you’ve found this post useful, or if you have a better approach, then please leave a comment below.

Do you need help adapting this to your needs?

I’m guessing the examples in this post didn’t exactly meet 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:

  1. Read other blogs, or watch YouTube videos on the same topic.  You will benefit much more by discovering your own solutions.
  2. Ask the ‘Excel Ninja’ in your office.  It’s amazing what things other people know.
  3. 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.
  4. 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:

9 thoughts on “VBA Code to Password Protect an Excel file

  1. Francis says:

    All the codes are helpful and provided description that are easily to understand. but, my concern is can you provide a specific location where should i put the block of codes. for example, this block of codes put it in module then this one for form load, and then this one is for workbook, etc. I’m frustrated to run the system because there are to many errors occurred. Please, I hope my suggestion will be accepted. Thank you more power.!

    • Excel Off The Grid says:

      Thank you for the feedback Francis. I will take this on board and include it as part of the next full site maintenance.

  2. Raajesh says:

    Hi
    I am trying to open an write protected Excel file using below code. This is giving me and error as “expected end of Statement ” Line 7 Char 35. Please help

    Option Explicit
    ExcelMacro
    Sub ExcelMacro()
    Dim xlApp
    Dim xlBook
    Set xlApp = CreateObject(“Excel.Application”)
    Set xlBook = xlApp.Workbooks.open “X:\Supply_Chain\ASR\Instock Report\Insotck from RMS\Daily In-Stock From RMS.xlsm”,_WriteResPassword:=”Wagwoord”
    xlBook.Save
    xlBook.Close
    xlApp.Quit

    Set xlBook = Nothing
    Set xlApp = Nothing

    End Sub

    • Excel Off The Grid says:

      Hi Raajesh

      The syntax of this line is incorrect:

      Set xlBook = xlApp.Workbooks.open “X:\Supply_Chain\ASR\Instock Report\Insotck from RMS\Daily In-Stock From RMS.xlsm”,_WriteResPassword:=”Wagwoord”
      

      Should be like this line:

      Set xlBook = xlApp.Workbooks.Open(Filename:="X:\Supply_Chain\ASR\Instock Report\Insotck from RMS\Daily In-Stock From RMS.xlsm", writeResPassword:="Wagwoord")
      
  3. Patrick Catthoor says:

    This approach works when the password is ‘hard-coded’ in vba, but what if I want to use Windows authentication (login en password on the company network) to grant different levels of access to different groups of users?

  4. Tim Smith says:

    Unfortunately, I cannot get this accomplished. I have tried the VBA coding as you have said, but when I save and then close and reopen the excel file, it opens without asking for a password. I don’t want to “protect” the file, I just want to encrypt the file with a password so that when I send the file to a vendor, they will have to enter the password to open the file.

    Any ideas?

  5. Marcus says:

    Hi,
    Thanks – this is a really useful site.
    I’m wondering if it’s possible to create a macro code that protects the VBA Project of a workbook?
    For context, I’ve written a macro that exports certain tabs from a model into a new “Extract” workbook, then super hides the tabs that I don’t want external stakeholders to see (such as calculations or inputs we’d rather they couldn’t access, but are required to enable the extract to still be dynamic).
    However, once the new workbook is created, it is possible for people to go into the VBA find all the tabs and make them visible again.
    Is it possible to automate this final level of protection? I’m making this model for people that aren’t very Excel savvy, hence needing to automate everything!
    Thanks

Leave a Reply

Your email address will not be published. Required fields are marked *