VBA Document.Protect未设置wdProtectionType(Office 2007)

Chr*_*bek 8 automation vba ms-word ms-office word-vba

我想自动执行仅使用Office 2007 VBA的Document.Protect保护word文档以进行注释的过程.如果文档还没有保护,这可以正常工作,但是一旦设置了保护,它就会失败.

以下是一个最小的工作示例,显示了我面临的错误(见下文).我在另一台运行Office 2007 SP3的PC上重现了.即使使用空白文档也会出现此问题.

要重现,请在保存新的空白文档后使用以下宏:

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
Run Code Online (Sandbox Code Playgroud)

之前调查的事情:

  • Office 2007是最新的SP 3和最新的Windows更新
  • 如果手动执行保护类型可以正确更改,但记录为宏失败.
  • 其他类型的保存文档(Document.Save或Document.SaveAs(2))
  • 禁用ReadingLayout ActiveWindow.View.ReadingLayout = False(请参阅Alredo的回答):Office 2007中没有变化

编辑:

  • 2015-10-23:初步问题
  • 2015-10-25:添加了最小的工作示例.
  • 2015-10-25:发现只有在手动或以编程方式设置保护类型后才能再更改.
  • 2015-10-26:提供赏金

小智 2

在网上做了一些研究后,代码对我来说失败了几次。我发现一篇文章解决了我的问题,该问题是由于 word 在阅读视图中打开受保护的文档而引起的。

这是原始帖子的链接帖子链接

Sub ProtectionBugOffice2007()

    Dim oDoc As Document

    ' Apply a first type of locking to simulate an existing lock
    Set oDoc = OpenRecentNotReadOnly

    If oDoc.ProtectionType <> wdNoProtection Then oDoc.Unprotect
    oDoc.Protect wdAllowOnlyFormFields
    oDoc.Close (wdSaveChanges)

    ' Now do the real test: Lock with our intended protection type
    Set oDoc = OpenRecentNotReadOnly
    oDoc.Unprotect
    oDoc.Protect wdAllowOnlyComments
    oDoc.Close (wdSaveChanges)

    ' Validate!
    Set oDoc = OpenRecentNotReadOnly
    If oDoc.ProtectionType = wdAllowOnlyComments Then
        MsgBox "Success!"
    Else
        MsgBox "Failure! Should be " & wdAllowOnlyComments & " but is " & oDoc.ProtectionType
    End If
    oDoc.Close

End Sub

' Function to open the document not in read only.
Function OpenRecentNotReadOnly() As Document

    Dim ret As Document

    Set ret = RecentFiles(1).Open
    ActiveWindow.View.ReadingLayout = False

    'Return the value
    Set OpenRecentNotReadOnly = ret
End Function
Run Code Online (Sandbox Code Playgroud)

我希望这有帮助 :)