I generally have a BAS
file containing the 'CreateWord' function which I drag into any workbook/database that needs it.
First it tests to see if Word is already open using GetObject
. If that returns an error it creates an instance of Word using CreateObject
.
The Word application can then be opened by simply using Set oWD_App = CreateWord
.
Sub Test()
Dim oWD_App As Object
Dim oWD_Doc As Object
Set oWD_App = CreateWord
With oWD_App
Set oWD_Doc = .Documents.Add
End With
End Sub
Public Function CreateWord(Optional bVisible As Boolean = True) As Object
Dim oTempWD As Object
On Error Resume Next
Set oTempWD = GetObject(, "Word.Application")
If Err.Number <> 0 Then
Err.Clear
On Error GoTo ERROR_HANDLER
Set oTempWD = CreateObject("Word.Application")
End If
oTempWD.Visible = bVisible
Set CreateWord = oTempWD
On Error GoTo 0
Exit Function
ERROR_HANDLER:
Select Case Err.Number
Case Else
MsgBox "Error " & Err.Number & vbCr & _
" (" & Err.Description & ") in procedure CreateWord."
Err.Clear
End Select
End Function