我想仅使用 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
之前调查的事情:
ActiveWindow.View.ReadingLayout = False
(请参阅 Alredo 的回答):Office 2007 中没有变化 编辑:
最佳答案
在网上做了一些研究并且代码在我身上失败了几次之后。我找到了一个帖子,解决了我的问题,这是因为 Word 在阅读 View 中打开 protected 文档。
这是原帖的链接Link to post
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
我希望这有帮助 :)
关于VBA Document.Protect 未设置 wdProtectionType (Office 2007),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33295905/