This post may contain affiliate links. Please read my disclosure for more info.

VBA Code to Password Protect an Excel file

VBA Code Snippets

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", _

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", _

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.

Want to Learn VBA & Macros?

If you want to automate Excel and save time, my recommended resouces for learning VBA Macros are: