Word as an OLE Automation Server
You can't use the GetObject function to open a Word document. Instead, use the CreateObject function and then open the file using the FileOpen statement, as shown in the following code:
Function OpenWordDoc ()
Dim objWordDoc As Object
Set objWordDoc = CreateObject("Word.Basic")
objWordDoc.FileOpen "C:\WORD6\MEMBER.DOC"
Set objWordDoc = Nothing
End Function
Here are a few things worth noting about this code:
- Although OLE automation creates and opens new instances of Microsoft Excel, it doesn't create or open new instances of Word.
- If Word isn't running, this code starts it, opens the document specified (you'll see it flash by on screen), and then closes both the document and Word. If Word is running, this code merely opens the document, not another instance of Word. It doesn't close either Word or the document. To close the document, add the following line of code before Set objWord = Nothing:
- Adding the last line, Set objWordDoc = Nothing, is good programming practice and mimics the handling of Microsoft Excel objects, but it's not necessary. Note that Word doesn't require (and doesn't support) code to formally quit the application.
- To leave users in Word, declare the object variable globally and comment out the last line.