Microsoft Office Tutorials and References
In Depth Information
If there isn’t a current instance of Word, using the GetObject function with no first argument
causes a run-time error. The On Error Resume Next line will allow the code to continue and
use the value in the wdApp variable to determine if a new instance of the application will be
opened. If the Word application is not loaded into memory, the code then uses the GetObject
function with a zero-length string as the first argument, which opens a new instance of Word.
Once the instance of Word has been identified, the procedure creates a new document. The
code also makes the new instance of Word visible, unlike our previous examples, where the
work was done behind the scenes without showing the Word window. The copied data is then
pasted at the end of the Word document. At the end of the procedure, the object variable wdApp
is released, but the Word window is accessible on the screen so that you can view the result.
The CreateNewWordDoc procedure demonstrates how to create a new document, but rather
than paste contents into the document the procedure enters the creation date of the file. The
program window is also closed, and the file is saved as NewWordDoc.doc.
Dim wrdApp As Word.Application
Dim wrdDoc As Word.Document
Dim i As Integer
Set wrdApp = CreateObject("Word.Application”)
wrdApp.Visible = True
Set wrdDoc = wrdApp.Documents.Add
.Content.InsertAfter "This document was created " & Date & " " & _
Time & "."
If Dir("C:\NewWordDoc.doc”) <> "" Then
Set wrdDoc = Nothing
Set wrdApp = Nothing
Controlling Excel from Other Office Applications
Now to go full circle, you should know how to reference the Excel Application object from
other Office applications. The same concepts apply; you must start by adding the Excel
Object Library to the procedure of the host application, if using early binding. Then you
must create an Excel object as outlined in Table 21-2.