VBA Code to Password Protect an Excel file

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

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.


Discover how you can automate your work with our Excel courses and tools.

Excel Academy

Excel Academy
The complete program for saving time by automating Excel.

Excel Automation Secrets

Excel Automation Secrets
Discover the 7-step framework for automating Excel.

Office Scripts Course

Office Scripts: Automate Excel Everywhere
Start using Office Scripts and Power Automate to automate Excel in new ways.

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

  1. 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.!

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

      Reply
  2. 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

    Reply
    • 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")
      
      Reply
  3. 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?

    Reply
  4. 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?

    Reply
  5. 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

    Reply

Leave a Comment