Pepacz
Pepacz

Reputation: 959

Activate Word window from Excel with VBA

I am trying access window of MS Word from Excel. I found methods to access a new Word document or a specific one, like the one at Copy Text from Range in Excel into Word Document,

But in my case I do not know the name of the document, it should be the last active one. I was hoping to use something like

Word.ActiveDocument

but no success. I also tried to simulat Alt+Tab keystroke to activate the window with

Application.SendKeys("%{TAB}")

but it does not work too. Any hint?

I am trying to create a macro that will just copy charts and some text around to Word and do some formating of the text along with it. So basically I can use any approach to this task. Thanks a lot.

Upvotes: 4

Views: 20917

Answers (1)

CuberChase
CuberChase

Reputation: 4518

You can access an open instance of Word by using late binding (http://support.microsoft.com/kb/245115) and GetObject. If you have multiple instances of Word open you are not guaranteed of getting any one of them in particular though.

Getting an instance of Word will allow you to access the ActiveDocument or the Application's current Selection. I'd still suggest doing some error checking to make sure you've got what you want.

    Sub GetWordDocument()
        Dim wdApp As Object

        'Turn off error handling since if the Application is not found we'll get an error
        'Use Late Binding and the GetObject method to find any open instances of Word
        On Error Resume Next
        Set wdApp = GetObject(, "Word.Application")
        On Error GoTo 0

        'Check to see if we found an instance.  If not you can create one if you desire
        If wdApp Is Nothing Then
            MsgBox "No instances of Word found"
            Exit Sub
        End If

        'Check if there are documents in the found instance of Word
        If wdApp.Documents.Count > 0 Then
            wdApp.Selection.TypeText "Cool, we got it" & vbCr

            'You can now access any of the active document properties too
            wdApp.ActiveDocument.Range.InsertAfter "We did indeed"
        End If

        'Clean up the Object when Finished
        Set wdApp = Nothing
    End Sub

Upvotes: 5

Related Questions