How to Edit a Read-Only Word Document (VBA)

谁说胖子不能爱 提交于 2020-01-17 08:37:08

问题


I am periodically getting Word documents from various clients and sometimes they send them to me in 'Read-Only' mode. While it isn't a big deal to go to 'View > Edit Document' manually, I cannot seem to find how to do this within my VBA code.

Either opening a document as editable or toggling it as editable once it is open would be sufficient for my needs.

Note that I cannot open the document with 'readOnly = false' as it looks like it is set to 'readOnly recommended' (based on my reading of the MS man page on Document.Open).

IN CONTEXT: I was also hitting a problem with turning off 'read-mode' which the documents were opening as by default. I have posted this question and answer here.


回答1:


The code below will change the ReadOnly attribute of a closed file, setting its ReadOnly attribute to either True or False depending on the argument supplied to the procedure.

Private Sub SetReadOnlyProperty(Fn As String, _
                                ByVal ReadOnly As Boolean)
    ' 21 Nov 2017

    Dim Fso As Object
    Dim Doc As Object

    Set Fso = CreateObject("Scripting.FileSystemObject")
    Set Doc = Fso.GetFile(Fn)

    If (Doc.Attributes And vbReadOnly) <> Abs(Int(ReadOnly)) Then
        Doc.Attributes = Doc.Attributes Xor vbReadOnly
    End If
End Sub

This procedure requires access to the MS Scripting Runtime DLL. Enable this access by checking the box against Miscrosoft Scripting Runtime from Tools >References in the VBE window. Below is an example of how to call the function. Note that an error will result if the supplied file doesn't exist.

Private Sub TestReadOnly()
    SetReadOnlyProperty "H:\Test Folder\Test File.docx", False
End Sub


来源:https://stackoverflow.com/questions/47360792/how-to-edit-a-read-only-word-document-vba

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!