在 docx 上使用 VBScript 时锁定编辑 [英] Locked for editing when using VBScript on docx
问题描述
我有一个使用 VBScript 从 .docx Word 文件中读取标题和文本的简单计划.
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 被锁定无法编辑"
"test.docx is locked for editing"
您将获得以下选项之一
- 打开只读副本
- 创建一个本地副本并稍后合并您的更改
- 在原始副本可用时接收通知
之后再次运行代码时出现错误
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
我的问题是你能做些什么来阻止这个锁定你正在处理的 Word 文件的循环(假设我在运行代码之前容易出错)?除了重命名文件和它的参考?
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?
推荐答案
由于文档在运行的隐形应用程序中保持打开状态,您收到错误消息.
You have got the error due to the document is staying opened within running invisible application.
IMO 的健壮方法是添加虚拟类来控制 word app 进程,然后在非常代码 sturtup 处创建该类的虚拟实例,这将在实例终止事件时退出 word app.
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
这篇关于在 docx 上使用 VBScript 时锁定编辑的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!