Although the Word applications visible property is set to Truethis code does not make the Word application the active application In most casesthe Word application icon stays in the taskbar and Excel remains the active application on the users screen

The following example uses errors to learn whether Word is already open before pasting a chart at the end of a document. If not, it opens Word and creates a new document:

Sub IsWordOpen() Dim wdApp As Object ActiveChart.ChartArea.Copy On Error Resume Next

Set wdApp = GetObject(, "Word.Application") If wdApp Is Nothing Then

Set wdApp = GetObject("", "Word.Application") With wdApp

.Documents.Add .Visible = True End With End If

On Error GoTo 0 With wdApp.Selection

.EndKey Unit:=wdStory .TypeParagraph

.PasteSpecial link:=False, DataType:=wdPasteOLEObject, _ Placement:=wdInLine, DisplayAsIcon:=False

End With

Set wdApp = Nothing End Sub

Using On Error Resume Next forces the program to continue even if it runs into an error. In this case, an error occurs when we attempt to link wdApp to an object that does not exist. wdApp will have no value. The next line, If wdApp Is Nothing then, takes advantage of this and opens an instance of Word, adding an empty document and making the application visible. Note the use of empty quotes for the first parameter in GetObject("", "Word.Application")—this is how to use the GetObject function to open a new instance of Word. Use On Error Goto 0 to return to normal VBA handling behavior.

0 0

Post a comment