Create Word file from Excel 2011

China☆狼群 提交于 2019-12-22 13:03:11

问题


The usual approach to create a Word document from Excel VBA:

Set WD = CreateObject("Word.Document")

results in an error when run with Excel 2011.

Any idea how a Word document can be created in Excel 2011 with VBA?

(I do not want to use AppleScript as I want the program to be able to run on PCs also.)


回答1:


The following code, based on the suggestion by bretville, seems to work both on mac (tested on Excel2011) and on pc (tested on Excel2007) and can be run repetedly, thus allowing creation of multiple Word files. What is required for the code to work under Excel2011 (mac) vba is a means to test if Word already is running or not. The approach is perhaps not the most elegant, but it works.

Dim word As Object
Dim doc As Object
On Error Resume Next
Set word = GetObject(, "word.application") 'gives error 429 if Word is not open
If Err = 429 Then
    Set word = CreateObject("word.application") 'creates a Word application
    Err.Clear
End If
word.Visible = True
Set doc = word.documents.Add

You may interchange the two Set word statements, which might seem preferable as no error code handling becomes necessary when run on pc, but the code for some reason then runs terribly slowly on the mac.




回答2:


For a PC I would do this:

Dim word As Object: Set word = CreateObject("word.application")
word.Visible = True
Dim doc As Object: Set doc = word.documents.Add


来源:https://stackoverflow.com/questions/8139792/create-word-file-from-excel-2011

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!