Word Document Password Protection - 2 most used Methods
Yes, there are more than one methods available to password protect a Word document. And it confused the programmers all the time about, which code to use to unprotect the document & read the content. Here are 2 of the most used methods:- Document level Password with Encryption
- Document level Protection for Editing.
1.VBA Macro to Open Word Document with Password Protection
A word document can be saved with protection on & a password set for encryption. This option can be found in this menu navigation- File -> Info -> Protect Document -> Encrypt with password
- Type password & click ok
- Save & close document
Sub openWordwithPassword()
'Define
Dim sFileName As String
Dim passwd As String
Dim oWord As Object
Dim oDoc As Object
'Init
Set oWord = CreateObject("Word.Application")
oWord.Visible = True
sFileName = "C:\Filepath.docx"
passwd = "enteryourpasswordhere"
'Open document using password
Set oDoc = oWord.Documents.Open(sFileName, PasswordDocument:=passwd)
'Do pocessing
Debug.Print oDoc.Content
oDoc.Save
'Save with password
oDoc.SaveAs Filename:=sFileName, Password:=passwd
'Close
oDoc.Close
End Sub
Once the document is opened using this method, its content can be edited or extracted. This is a document level password protection. In case your document is only writeprotected, then use the below method.
2. VBA Code to Unprotect Word Document - Enable Editing
The below code unprotects a word document with password for readonly. Then in the next step, you will be able to edit or read contents Then, after processing the data, the code enables writeProtection on the document. i.,e edit is disabled & file is saved.Sub UnprotectwordwithPassword()
'Define
Dim sFileName As String
Dim passwd As String
Dim oWord As Object
Dim oDoc As Object
'Init
Set oWord = CreateObject("Word.Application")
oWord.Visible = True
sFileName = "C:\Filepath.docx"
passwd = "enteryourpasswordhere"
'Open document using password
Set oDoc = oWord.Documents.Open(sFileName, PasswordDocument:=passwd)
If ActiveDocument.ProtectionType <> -1 Then oDoc.Unprotect passwd
'Do pocessing
Debug.Print oDoc.Content
'Protect again with password
objDoc.Protect 3, , passwd '3- - Refer end of the page for more parameters
oDoc.Save
'Close
oDoc.Close
End Sub
This VBA code is very useful, then you have multiple files to be marked as readonly or protected from users editing it. It is tough to open and edit each document one by one and then enable a password.
Instead, with this process, you can place all the word documents in a folder. Then make the macro to read files one by one and enable password protection.
With document.Protect function You can use one of these parameters which serves different purpose.
-> wdProtectionType & corresponding value
- wdAllowOnlyComments = 1
- wdAllowOnlyFormFields = 2
- wdAllowOnlyReading = 3
- wdAllowOnlyRevisions = 0
- wdNoProtection = -1