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.)
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