Opening a Document in Word

If you want to open a file created in another Office application, you can use the GetObject function to directly open the file. However, it is just as easy to open an instance of the application and open the file from the application. Another use of GetObject is examined shortly.

If you are not familiar with the Word object model, you can use the Word macro recorder to discover which objects, properties, and methods you need to use to perform a Word task that you can do manually.

The following code copies a range in Excel to the clipboard. It then starts a new instance of Word, opens an existing Word document, and pastes the range to the end of the document. Because the code uses early binding, make sure you establish a reference to the Word object library:

Sub CopyTableToWordDocument()

'Example of Word automation using early binding

'Copies range from workbook and appends it to existing Word document Dim wdApp As Word.Application

'Copy A1:B6 in Table sheet


'Establish link to Word

Set wdApp = New Word.Application

With wdApp

'Open Word document

.Documents.Open Filename:="C:\VBA_Prog_Ref\Chapter19\Table.docx" With .Selection

'Go to end of document and insert paragraph

.EndKey Unit:=wdStory


'Paste table


End With

.ActiveDocument.Save 'Exit Word .Quit End With

'Release object variable Set wdApp = Nothing End Sub

The New keyword creates a new instance of Word, even if Word is already open. The Open method of the Documents collection is used to open the existing file. The code then selects the end of the document, enters a new empty paragraph, and pastes the range. The document is then saved and the new instance of Word is closed.

0 0


  • Sebastian
    How to reference a cell in a word table?
    8 years ago

Post a comment