If you've hung around here for a little while, then you probably already know that you can use the WIN32OLE.connect() method to connect to a running instance of applications like Microsoft Word. Just pass the method the ProgID of the Application object:
word = WIN32OLE.connect('Word.Application')
That works great if you have just one instance of the application running, with one or multiple documents open. But suppose you have multiple instances of the application running? How can you be sure that you connect to the instance with Document B, and not the instance with Document A?
Well, assuming that Document B has been saved and you know the full filename, then you can connect to the Document object, rather than to the Application object. And you do this by passing the WIN32OLE.connect() method the full filename:
document = WIN32OLE.connect('C:\Path To File\DocumentB.doc')
This returns an instance of the Word.Document object. You can then grab
an instance of that Document's Application object:
word = document.Application
This works with other multiple-instance applications, such as Excel. The following code connects to a specific instance of an Excel.Workbook object:
workbook = WIN32OLE.connect('C:\Path To File\WorkbookB.xls')
xl = workbook.Application
By the way, some applications, such as PowerPoint, are single-instance applications, so there will never be multiple instances of the application running, avoiding the need to use the process outlined above.
There you have it. Please let me know if you have specific questions or suggestions for future articles.
Thanks for stopping by!