How to Password Protect Microsoft Word Using VBA Code

VBA (Visual Basic for Applications) is a programming language that allows you to automate certain tasks in Microsoft Applications. if you’re looking to Password Protect your Microsoft Word Application or a specific Document using VBA Code but you are not sure how to do it, this tutorial is for you. In this blog post I explain how to do it using small piece of VBA code that add Password Protection to your Microsoft word.

Here is a simple, step-by-step guide to Password Protect your Word using VBA Code:

  1. Open VBA Editor by Pressing Alt+F11 Shortcut from your Keyboard.
  1. Insert New Model : Click on insert -> then Select Module
VBA Code Editor
  1. Past the following Code into the Module, Press Ctrl+S and the close VBA Editor.
Sub AutoExec()
    Dim userPassword As String
    Dim correctPassword As String
    Dim userResponse As String
    Dim retryCount As Integer
    Dim maxRetries As Integer
    correctPassword = "YourPassword123"
    maxRetries = 3
    retryCount = 0
        Do
            userResponse = InputBox("Please enter Your password to Open Word:", "Password Required")
            If userResponse = correctPassword Then
                MsgBox "Password accepted.", vbInformation, "Access Granted"
                Exit Do
            Else
                retryCount = retryCount + 1
                If retryCount >= maxRetries Then
                    MsgBox "Incorrect password entered too many times. Word going to close.", vbCritical, "Access Denied"
                    Application.Quit
                    Exit Sub
                Else
                    MsgBox "Incorrect password. Please try again. You have " & (maxRetries - retryCount) & " attempts left.", vbCritical, "Access Denied"
                End If
            End If
        Loop
    
End Sub

if you want to Password a specific Word Document not whole application past the following code into the module

Sub AutoOpen()
    Dim password As String
    Dim userPassword As String
    password = "yourpassword"  
    userPassword = InputBox("Enter the password to access Word:")
    If userPassword <> password Then
        MsgBox "Incorrect password. Word will now close."
        Application.Quit
    End If
End Sub

Note: Using the above VBA code you can also Password Protect other Microsoft Applications such as Excel or PowerPoint.

  1. Close Microsoft Word.
Password protect Microsoft Word using VBA  Code
  1. Now, each time you open Microsoft Word, a password prompt will appear, asking you to enter the password.
Password Protected Microsoft Word

Click here to learn more about how to use and run VBA Code

I hope this tutorial will helps you to Password Protect your Microsoft Word Applications using VBA Code.

If You have any question Suggestion of Feedback feel free to contact us using the details provided on our contact us page.

Thank you.

Similar Posts