aegit
aegit

Reputation: 33

How to select a running instance of Word and open a Document within

So here is what I want to do:

I have a VBA-application that uses information of multiple open Word-2010 Documents. This works fine as long as all open Documents are opened within the same process. But I would like to open these Documents not manually but via Powershell and so far I have only been able to do so by starting a new instance of Word. Let's have a look at the code:

$isRunning = (Get-Process | Where-Object { $_.Name -eq "WINWORD" }).Count -gt 0

if ($isRunning) {

    #Select open Word Process
    **$wrd = # ???** 

    # Make Word Visible 
    $wrd.visible = $true  

    # Open a document  
    $doc = $wrd.documents.add($latest.Fullname)  
}
else {

    # Create Word Object  
    $wrd = New-object -com word.application 

    # Make Word Visible 
    $wrd.visible = $true  

    # Open a document  
    $doc = $wrd.documents.add($latest.Fullname)  
}

The ??? mark the spot where I would like to Select a running instance of Word in which I can open my docs. But all examples I could find always invoke a new object by starting a separate instance of word.

Another workaround would be to change my VBA application to access Documents of different processes, but I don't know if that is even possible or how to do it.

Either way, any help would be highly appreciated.

Thanks.

Upvotes: 3

Views: 1031

Answers (1)

David Brabant
David Brabant

Reputation: 43559

You can get a running instance like this:

$word = [System.Runtime.InteropServices.Marshal]::GetActiveObject('Word.Application')

Upvotes: 2

Related Questions