Word vba document.readonly状态错误地返回false

我有一个Excel项目,检查单词文件的更改修改date,如果更改,它将打开该文档,并从Word表单字段中的文本导入到Excel中。

在excel中打开和导入word文档的例程如下:

Sub CopyFromWord(pFile as String,aFile as string) Dim wdApp As Object On Error Resume Next Set wdApp = GetObject(, "Word.Application") If Err.Number <> 0 Then Set wdApp = CreateObject("Word.Application") Else 'word is already running End If On Error Goto 0 Set wdDoc = wdApp.Documents.Open(Filename:="" & pFile & "", ReadOnly:=True) wdApp.Visible = False For Each c In wdDoc.bookmarks 'removed code that copies values from word doc fields to excel sheet Next c wdApp.Activedocument.Close SaveChanges:=False End Sub 

单词文件都是作为同一个文件的副本而开始的。 有几千个文件的副本,但每个都位于自己的文件夹中,具有唯一的名称。

用户find他们需要的文件夹并在其中打开单词文档。 它调出一个用户表单,然后用input到用户表单的方式填充文档中的表单域。 一个命令button然后保存并退出表单。

由于欢迎消息/用户窗体在文档打开时自动加载,因此我将以下代码添加到文档的打开事件中:

 Sub Document_Open() If ThisDocument.ReadOnly = True then Exit Sub msgbox "Welcome " & Environ$("Username") & ". Click OK to begin." Userform1.show End sub 

这确保了当Excel项目循环遍历所有文件时,如果发现有变化,就需要打开文件(只读),这样可以导入数据,而不会被用户表单/欢迎信息中断,closures它,并进行search循环所有文件检查更改的修改date。

它应该不断运行,但是,大约20%的时间,一个文档将被打开,只能被excel代码读取,但word文档中的欢迎信息框将显示,表明这个文档。只读错误地返回false。 如果我在这种情况下debuggingWord文档,那么

 ? thisdocument.readonly 

我得到一个“假”的结果。 但是,即使是单词文档的标题栏以“(只读)”结尾,所以显然已经以只读方式打开,因此只读应该返回True。

它不是特定于任何文档,如果我试图重复打开它,它似乎在下一次工作(在它正确地注册一个只读,并退出子之前的消息框代码)。 我找不到任何一种模式,不能在网上find任何信息,我已经search了几个星期!

可能不会被认为是答案,但是根据蒂姆·威廉的build议,我设法把这个完全解决了我的问题。 我起初挣扎,因为我试图过早设置财产。 完整的代码如下:

  Sub CopyFromWord(pFile as String) Dim wdApp As Object On Error Resume Next Set wdApp = GetObject(, "Word.Application") If Err.Number <> 0 Then Set wdApp = CreateObject("Word.Application") Else 'word is already running End If On Error Goto 0 'save current setting secAutomation = wrdApp.Application.AutomationSecurity 'set Word to disable macros when a document is opened via vb: wrdApp.Application.AutomationSecurity = msoAutomationSecurityForceDisable '(without using wrdApp prefix it would only apply to the code's App ie Excel) Set wdDoc = wdApp.Documents.Open(Filename:="" & pFile & "", ReadOnly:=True) wdApp.Visible = False For Each c In wdDoc.bookmarks 'removed code that copies values from word doc fields to excel sheet Next c 'restore original setting before closing wrdApp.Application.AutomationSecurity = secAutomation wdApp.Activedocument.Close SaveChanges:=False End Sub 

非常感谢Tim Williams的链接,以及在链接内容中提供代码的人。 这是如此的帮助,最受赞赏。