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)
- Type: The type of protection to be applied
- 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 wdAllowOnlyFormFields, NoReset is ignored.
- Password: If supplied, the password to be able to edit the document, or to change or remove protection.
- UseIRM: Specifies whether to use Information Rights Management (IRM) when protecting the document.
- EnforceStyleLock: Specifies whether formatting restrictions are enforced for a protected document.
Lock Types are derived from WdProtectionType enum and has following constants:
Lock Types
- wdAllowOnlyComments: Only comment would be allowed
- wdAllowOnlyFormFields: Only form fields would be allowed
- wdAllowOnlyReading: Only reading would be allowed means no insertion, formatting, editing, deleting would be allowed
- wdAllowOnlyRevisions: track revision would be allowed
- 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