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

230 Views Asked by At

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.

1

There are 1 best solutions below

2
NickSlash On

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 ' not desired
End With

End Sub

Update

I'm using Office 2016, so might not be the case for you. Using Word VBA I can open a document (with form fields and has wdAllowOnlyReading set) in Read-Only mode:

Dim Doc As Document: Set Document = Word.Documents.Open(FileName:"example.doc", ReadOnly:=True)

I am still able to use VBA to unprotect, modify form fields and re-protect this document even though it is read only. So there should be no need to open in ReadWrite and then change to ReadOnly.

Still, Add(ing) your template document instead of Open(ing) it seems like a better option to stop it from being modified.