Creating a New Word Document

Say you want to use a current instance of Word if one exists, or if there is no current instance, you want to create one. In either case, you want to open a new document and paste the table into it. The following code shows how to do this. Again, you are using early binding:

Sub CopyTableToAnyWordDocument()

'Example of Word automation using early binding 'Copies range from workbook and pastes it in 'a new Word document, in a active instance of 'Word, if there is one. 'If not, opens new instance of Word

Dim wdApp As Word.Application

'Copy Range A1:B6 on sheet named Table ThisWorkbook.Sheets("Table").Range("A1:B6").Copy

On Error Resume Next

'Try to establish link to open instance of Word Set wdApp = GetObject(, "Word.Application")

'If this fails, open Word If wdApp Is Nothing Then

Set wdApp = GetObject("", "Word.Application") End If

On Error GoTo 0

With wdApp

'Add new document .Documents.Add 'Make Word visible .Visible = True End With

With wdApp.Selection

'Go to end of document and insert paragraph

.EndKey Unit:=wdStory


'Paste table


End With

'Release object variable Set wdApp = Nothing End Sub

If there is no current instance of Word, using GetObject with no first argument causes a run-time error, and the code then uses GetObject with a zero-length string as the first argument, which opens a new instance of Word, and then creates a new document. The code also makes the new instance of Word visible, unlike the previous examples, where the work was done behind the scenes without showing the Word window. The table 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.

0 0

Post a comment