如何从 Excel 确定特定的 Word 文档是否打开?
How to make sure from Excel that a specific Word document is open or not?
我希望我的 excel 宏通过在我放置在模板 word 文档中的书签后插入电子表格数据来创建报告。
但我发现如果模板word文档已经打开,宏会崩溃,因此模板文档将被锁定为只读,无法再访问由宏。
有没有办法即使模板word文档已经打开也能防止then宏崩溃?
下面是我的代码
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
这里是评论中建议的演变:
一个测试文件是否打开的功能,并让您在测试时直接设置它。
使用方法:
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 应用程序的参考...
欢迎任何suggestion/evolution!
我希望我的 excel 宏通过在我放置在模板 word 文档中的书签后插入电子表格数据来创建报告。
但我发现如果模板word文档已经打开,宏会崩溃,因此模板文档将被锁定为只读,无法再访问由宏。
有没有办法即使模板word文档已经打开也能防止then宏崩溃?
下面是我的代码
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
这里是评论中建议的演变:
一个测试文件是否打开的功能,并让您在测试时直接设置它。
使用方法:
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 应用程序的参考...
欢迎任何suggestion/evolution!