Automatically switch document protection on/off

User avatar
HansV
Administrator
Posts: 78487
Joined: 16 Jan 2010, 00:14
Status: Microsoft MVP
Location: Wageningen, The Netherlands

Automatically switch document protection on/off

Post by HansV »

If you protect a document for forms, you can specify that some sections remain unprotected. In unprotected sections, the user can enter and edit text freely. But many Word features are still disabled in an unprotected section.
To get around this, you can use code that unprotects the entire document when the insertion point is in an unprotected section and protects it again as soon as the user moves to a protected section. The code uses a class module and an application-level event handler.

You MUST specify which sections are to be protected and which ones aren't before activating the code, otherwise you may end up with a locked document.

If it goes wrong, temporarily comment out the code in the class module. You can then unprotect the document.

In a class module named clsEvents:

Code: Select all

Public WithEvents app As Word.Application

' In this example, the first section is protected, and the second one unprotected
' You can modify the code for other setups

Private Sub app_WindowSelectionChange(ByVal Sel As Selection)
  If Sel.Information(wdActiveEndSectionNumber) = 1 And _
      ActiveDocument.ProtectionType = wdNoProtection Then
    ActiveDocument.Protect NoReset:=True, Type:=wdAllowOnlyFormFields
  ElseIf Sel.Information(wdActiveEndSectionNumber) = 2 And _
      ActiveDocument.ProtectionType = wdAllowOnlyFormFields Then
    ActiveDocument.Unprotect
  End If
End Sub
In a standard module:

Code: Select all

Public MyClass As New clsEvents
And in the ThisDocument module:

Code: Select all

Private Sub Document_Open()
  Set MyClass.app = Application
End Sub
Here is a sample document (Word 2007-2010 .docm)
ProtectUnprotect.docm
(This is another oldie from Woody's Lounge)
You do not have the required permissions to view the files attached to this post.
Best wishes,
Hans