Create Word file from Excel 2011

会有一股神秘感。 提交于 2019-12-06 08:10:39

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.

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