如何确定从Excel的特定的Word文档是否打开?

我希望我的Excelmacros可以通过在放置在模板文档中的书签之后插入电子表格数据来创build报告。

但是我发现, 如果模板文档文档已经打开,macros将会崩溃 ,因此模板文档将被locking为只读且不能被macros访问。

有没有办法来防止即使模板word文档已经打开,然后macros崩溃

以下是我的代码

Set wdApp = CreateObject("Word.Application") 'Create an instance of word Set wdDoc = wdApp.Documents.Open(ThisWorkbook.Path & "\Templates\Template_Confirmation.docx") 'Create a new confirmation note 

这里有一个在评论中build议的进化:

一个函数,用于testing文件是否打开,并提供在testing时直接设置的function

如何使用它 :

 Sub test() Dim WdDoc As Word.Document Set WdDoc = Is_Doc_Open("test.docx", "D:\Test\") MsgBox WdDoc.Content WdDoc.Close Set WdDoc = Nothing End Sub 

而function:

 Public Function Is_Doc_Open(FileToOpen As String, FolderPath As String) As Word.Document 'Will open the doc if it isn't already open and set an object to that doc Dim wrdApp As Word.Application Dim wrdDoc As Word.Document On Error Resume Next 'Set wrdApp = GetObject(, "Word.Application") If wrdApp Is Nothing Then Set wrdApp = CreateObject("Word.Application") Set wrdDoc = wrdApp.Documents.Open(FolderPath & FileToOpen) Else On Error GoTo NotOpen Set wrdDoc = wrdApp.Documents(FileToOpen) GoTo OpenAlready NotOpen: Set wrdDoc = wrdApp.Documents.Open(FolderPath & FileToOpen) End If OpenAlready: On Error GoTo 0 Set Is_Doc_Open = wrdDoc Set wrdApp = Nothing Set wrdDoc = Nothing End Function 

唯一的缺点,你没有Word应用程序的参考…

任何暗示/进化是受欢迎的!