Target a specific Document from the active Word windows through COM

Put simple Tips and Tricks that are not entire Tutorials in this forum
Renets
Posts: 24
Joined: 12 Jul 2018, 13:11

Target a specific Document from the active Word windows through COM

28 Jul 2019, 20:23

Recently I was dealing with a problem that wouldn't even let me perform any COM action in Word, but it looked I just needed to restart the computer so silly, here is the link:

https://www.autohotkey.com/boards/viewtopic.php?f=76&t=66595

While figuring that out, I found another problem I needed to get over, I needed to be able to target a specific document within the active Word windows, after a lot after a lot of research and tests, I finally found a solution that is somehow similar to how you target specific Sheets in Excel, which is like this:

Code: Select all

sheet5_cellA5_value := oExcel.Application.Sheets("Sheet5").Range("A5").Value ; Target sheet is "Sheet5"
So the solution for Word is this

Code: Select all

oWord := ComObjActive("Word.Application") ; Object for Word
oWord.Documents("Document2.docx").ActiveWindow.Selection.TypeText("HI") ; Target document "Document2" and execute the command"TypeText" with the text "Hi"
The key command here is .ActiveWindow. Without it, it will throw you an error about not finding the "Selection" command

Couple of notes:
  • The document have to be saved in the computer, I test it without saving it and then it didn't worked, when I save it (anywhere on the PC), it worked
  • The document must be opened in a window. If the document isn't opened in a window you won't be able to do any action
  • It doesn't matter if the target document is minimized
Now you can perform any controled action to a target document, even if you are working in another active document :dance:

I hope this is useful to you, thanks! :thumbup:

Return to “Tips and Tricks”

Who is online

Users browsing this forum: No registered users and 21 guests