如何使用VBA通过Excel修改已打开的Word文档? 这里有一些我写的代码,但是我无法理解。
Dim WordDoc As Word.Document
Dim WordApp As Word.Application
'ThisWorkbook is the opened Excel Workbook through which I control Word documents.
If Len(Dir(ThisWorkbook.path & "\Report.docx")) <> 0 then
'if the document exists in the folder where ThisWorkbook is saved, I check
'if the document is already opened.
If IsFileOpened(ThisWorkbook.path & "\Report.docx")
'if during the run-time I get here, it means that the document exists and
'it's already opened.
'Now I want to get the reference to the opened document "Report.docx",
'so I do a thing like this.
Set WordDoc= Word.Application.Documents(ThisWorkbook.path & "\Report.docx")
'When it tries to excute the instruction over, it gives me a message in which
'it is written that the name is bad or inexistent, even if the document
'is already opened. Is the instruction correct?
Set WordApp= WordDoc.Application
'...other code
Else
'if the document isn't opened, I open it.
Set WordApp = CreateObject("Word.Application")
Set WordDoc = WordApp.Documents.Open(ThisWorkbook.path & "\Report.docx")
'..other code
End If
Else 'I create a new document called "Report.docx" if it doesn't exist
'in the folder where ThisWorkbook is saved.
Set WordApp = CreateObject("Word.Application")
Set WordDoc = WordApp.Documents.Add("Report.docx")
'.... other code
End If
提前致谢...
答案 0 :(得分:0)
我尝试使用excel工作簿并且它有效
Set WordDoc= Word.Application.Documents(ThisWorkbook.path & "\Report.docx")
应该是
Set WordDoc= Word.Documents("Report")
当我尝试使用文件路径时,我得到了运行时错误&#34; 9&#34;下标超出范围。当我只使用文件名时,它就成功了。
编辑:使用word文档尝试此操作后,您不需要应用程序对象,也不应使用文件扩展名。我可以确认这是有效的。
答案 1 :(得分:0)
我试过这个版本
path = ThisWorkbook.path & "\Report.docx"
Set WordApp = GetObject(path).Application
取代
Set WordDoc= Word.Application.Documents(ThisWorkbook.path & "\Report.docx")
它有效。