Protect/Unprotect a Word Document using VBA, C#, VB.Net example

Protect/Unprotect a Word Document using VBA, C#, VB.Net example

Protect/Unprotect

Prevent editing or deleting or adding contents in the word document. Considering that user is having sensitive information which he/she doesn’t wish to allow anyone to modify in the document. In this article we are using VBA, VSTO (Visual Studio Tools for office) in C# and VB.Net code style hence following prerequisites are recommended:

Syntax

Document.Protect(Type, NoReset, Password, UseIRM, EnforceStyleLock)

  1. Type: The type of protection to be applied
  2. NoReset: False to reset form fields to their default values; True to retain the current form field values if the document is protected. If Type is not wdAllowOnlyFormFieldsNoReset is ignored.
  3. Password: If supplied, the password to be able to edit the document, or to change or remove protection.
  4. UseIRM: Specifies whether to use Information Rights Management (IRM) when protecting the document.
  5. EnforceStyleLock: Specifies whether formatting restrictions are enforced for a protected document.

Lock Types are derived from WdProtectionType enum and has following constants:

Lock Types

  1. wdAllowOnlyComments: Only comment would be allowed
  2. wdAllowOnlyFormFields: Only form fields would be allowed
  3. wdAllowOnlyReading: Only reading would be allowed means no insertion, formatting, editing, deleting would be allowed
  4. wdAllowOnlyRevisions: track revision would be allowed
  5. wdNoProtection: no protection

C# Code example

private void btnProtect_Click(object sender, RibbonControlEventArgs e)
{
	//bind active document reference
	wordApp.Document oDocument = Globals.ThisAddIn.Application.ActiveDocument;

	//Protect document
	oDocument.Protect(wordApp.WdProtectionType.wdAllowOnlyReading,System.Reflection.Missing.Value,"password");

}

Unprotect

Document.Unprotect(“password”);

VB.Net code example

Private Sub btnProtectdocument_Click(sender As Object, e As RibbonControlEventArgs) Handles btnProtectdocument.Click
    
    'Declare document object variable
    Dim oDocument as word.Document
    
    'Set the reference of active document
    oDocument=Globals.ThisAddIn.Application.ActiveDocument
    
    'Perform protection
    oDocument.Protect(WdProtectionType.wdAllowOnlyReading,vbNull,"password")
End Sub

VBA code example

Public Sub ProtectDocumentExample()
    Dim oDocument As Document
    Set oDocument = ActiveDocument
    
    'Protect document for readonly
    oDocument.Protect wdAllowOnlyReading, , "password"
End Sub

Output

Next >> Document object a complete reference Word with VBA

Leave a Reply

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