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

时间:2015-07-08 08:44:25

标签: excel vba excel-vba ms-word word-vba

我希望我的excel宏通过在我放置在模板word文档中的书签之后插入电子表格数据来创建报告。

但是我发现如果模板word文档已经打开,宏将崩溃,因此模板文档将被锁定为只读,宏不再可访问。

是否有方法可以防止宏崩溃,即使模板文档已经打开

以下是我的代码

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

1 个答案:

答案 0 :(得分:1)

以下是评论中建议的演变:

功能,用于测试文件是否已打开,并允许您在测试时直接设置

如何使用它:

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

功能:

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应用程序的参考...

欢迎任何建议/演变!