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

Generate accurate VBA code in seconds with AutoMacro

AutoMacroExample

AutoMacro is a powerful VBA code generator that comes loaded with an extensive code library and many other time-saving tools and utilities.

Whether you’re an experienced coder looking to save time, or a newbie just trying to get things to work, AutoMacro is the tool for you.

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.

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:

4 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")
      

Leave a Reply

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