Reputation: 6949
I have a simple plan to read the header and text from a .docx Word file using VBScript.
So far so good. However, if you make a mistake in your code it'll lock up the document you are working with:
"test.docx is locked for editing"
You get given the options of one of the following
After which when running the code again I get the error
The requested member of the collection does not exist.
Dim Word, WordDoc, myDoc, srcDoc
myDoc = "D:\temp\test.docx"
Set Word = CreateObject("Word.Application")
'Open the Document
Set WordDoc = Word.Documents.open(myDoc)
' do stuff with the doc
' and include this to "lock" the document
With WordDoc.Sections(1)
.Headers(wdHeaderFooterPrimary).Range.Text = "Header text"
End With
' Close Word
WordDoc.Save
Word.Quit
'Release the object variables
Set WordDoc = Nothing
Set Word = Nothing
My question is what can you do to stop this cycle of locking up the Word file that you are working on (assuming I'm prone to errors before running the code) ? Apart from renaming the file and it's reference?
Upvotes: 1
Views: 843
Reputation: 12602
You have got the error due to the document is staying opened within running invisible application.
IMO the robust way is to add dummy class to control word app process, then create dummy instance of the class at the very code sturtup, which will quit word app on instance termination event.
Dim Word, WordDoc, myDoc, Dummy
Set Dummy = New cDummy
myDoc = "D:\temp\test.docx"
Set Word = CreateObject("Word.Application")
Word.Visible = True ' just for debug
' Open the Document
Set WordDoc = Word.Documents.open(myDoc)
' do stuff with the doc
' raise the error to terminate
MsgBox 1/0
Class cDummy
Private Sub Class_Terminate()
On Error Resume Next
WordDoc.Save
WordDoc.Close
Word.Quit
MsgBox "Word App Quit"
End Sub
End Class
Upvotes: 1