简体   繁体   中英

How to make a word document readonly in runtime after opening without closing it before

Is it possible to make a word document ReadOnly in runtime after it has been opened in ReadWrite mode without closing it before?

Here is an example what I try to do:


Sub ProcessWordDoc()
Dim WordApp As New Word.Application
Dim Doc As Word.Document

WordApp.Visible = True

Set Doc = WordApp.Documents.Open(Filename:="C:\myWordTemplate.docx", ReadOnly:=False)

With Doc
    .Unprotect
    
    .FormFields("Firstname").Result = Me.Firstname
    .FormFields("Lastname").Result = Me.Lastname
    
    .Protect wdAllowOnlyReading
End With

' Make Doc ReadOnly after the document has been processed.
' Somthing like, but it does not work, since the ReadOnly property is read-only ;-)
Doc.ReadOnly = True

End Sub

So in a nutshell: is it possible to switch the mode of a word document via VBA from ReadWrite to ReadOnly?

Thanks for an help.

Expanding on my comment/alternative idea.

This will (should) create a new document from your template file, protect it after inserting the data and then "save" the document so it can be closed without being prompted to save it, so no new document is saved and your template is never edited.

Sub Main()
Dim WordApp As New Word.Application
Dim Doc As Word.Document

WordApp.Visible = True

Set Doc = WordApp.Documents.Add(Template:="C:\myWordTemplate.docx")

With Doc
    .Unprotect
    .FormFields("Firstname").Result = Me.Firstname
    .FormFields("Lastname").Result = Me.Lastname
    .Protect wdAllowOnlyReading
    .Saved = True
End With

End Sub

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM