Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

VBA Document.Protect not setting wdProtectionType (Office 2007)

Tags:

I would like to automate the process of protecting a word document for comments only using Office 2007 VBA's Document.Protect. This works fine if the document has no protection yet, but fails once the protection has ever been set before.

The following is a minimal working example that shows the bug I am facing (see below). I have reproduced on another PC running Office 2007 SP3. The problem occurs even with a blank document.

To reproduce, use the following macro after saving a new blank document:

Sub ProtectionBugOffice2007()

    ' Apply a first type of locking to simulate an existing lock
    RecentFiles(1).Open
    If ActiveDocument.ProtectionType <> wdNoProtection Then ActiveDocument.Unprotect
    ActiveDocument.Protect wdAllowOnlyFormFields
    ActiveDocument.Close (wdSaveChanges)

    ' Now do the real test: Lock with our intended protection type
    RecentFiles(1).Open
    ActiveDocument.Unprotect
    ActiveDocument.Protect wdAllowOnlyComments
    ActiveDocument.Close (wdSaveChanges)

    ' Validate!
    RecentFiles(1).Open
    If ActiveDocument.ProtectionType = wdAllowOnlyComments Then
        MsgBox "Success!"
    Else
        MsgBox "Failure! Should be " & wdAllowOnlyComments & " but is " & ActiveDocument.ProtectionType
    End If
    ActiveDocument.Close

End Sub

Things investigated before:

  • Office 2007 is up to date with SP 3 and latest windows update
  • If performed manually protection type can be changed correctly, but recorded as macro fails.
  • Other types of saving the document (Document.Save or Document.SaveAs(2))
  • Disabling ReadingLayout ActiveWindow.View.ReadingLayout = False (see Alredo's answer): No change in Office 2007

Edits:

  • 2015-10-23: Initial problem
  • 2015-10-25: Minimal working example added.
  • 2015-10-25: Discovered that only after manually or programmatically setting the protection type it can no longer be changed.
  • 2015-10-26: Offered bounty