Locked for editing when using VBScript on docx

落花浮王杯 提交于 2019-12-24 10:49:47

问题


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

  • Open a Read Only copy
  • Create a local copy and merge your changes later
  • Receive notifications when the original copy is available

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?


回答1:


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


来源:https://stackoverflow.com/questions/56893444/locked-for-editing-when-using-vbscript-on-docx

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