Reuse COM Object Topic is solved

Get help with using AutoHotkey (v1.1 and older) and its commands and hotkeys
ShubhamM
Posts: 38
Joined: 08 Nov 2017, 21:38

Reuse COM Object

Post by ShubhamM » 04 Mar 2022, 13:44

I have file (template) that I open, modify, and then save to its designated folder in one command via ComObjCreate. From here, I want to run other commands on the same file but after releasing it and by using ComObjActive.

I'm able to restart my script or close the file and then reopen it to use ComObjActive but I want to know if it's possible for me to avoid doing either. Essentially, how do I release the COM object (file/application) such that ComObjActive can be used immediately after? E.g. I want to be able to do the following:

Code: Select all

F1::
Word_App := ComObjCreate("Word.Application")
Word_File := Word_App.Documents.Open("TestFile.docx")
Word_App.Visible := 1
Word_App.Activate
/*
Do Stuff
*/
Word_File.SaveAs(A_Desktop "\Test.docx")
;The Word File remains open for the user. How do I release the COM Object here,
;without using "Word_App.Quit", which closes the application and the open file?
Return 

F2::
Word_Application := ComObjActive("Word.Application") 
;This doesn't work (it doesn't select the word file that was opened with ComObjCreate)
PDF_FullPath := StrReplace(Word_Application.ActiveDocument.FullName, ".docx", ".pdf")
ActiveDocument.SaveAs2(PDF_FullPath, 17)
Return
Thank you so much for any assistance you can provide!

User avatar
flyingDman
Posts: 2848
Joined: 29 Sep 2013, 19:01

Re: Reuse COM Object  Topic is solved

Post by flyingDman » 04 Mar 2022, 14:11

After you use Word_App := ComObjCreate("Word.Application") the link with MS Word will continue to exist until Word_App.quit() or the user manually closes the App. While the COM link exist, do not use ComObjActive("Word.Application"). If you want to close a document Word_File.close(0) or Word_File.close(-1). This will not quit the App. To reopen the doc, use Word_App.Documents.Open(path) again.

The last 2 lines contain errors. Should be:

Code: Select all

PDF_FullPath := StrReplace(Word_App.ActiveDocument.FullName, ".docx", ".pdf")
Word_App.ActiveDocument.SaveAs2(PDF_FullPath, 17)
14.3 & 1.3.7

ShubhamM
Posts: 38
Joined: 08 Nov 2017, 21:38

Re: Reuse COM Object

Post by ShubhamM » 04 Mar 2022, 14:44

Thank you for the information provided.

I apologize for the mistakes in my code; I have those all working on my end - I just copied, pasted, and edited incorrectly.

I found a rather easy solution for my problem thanks to the information you provided, where I simply use an if-statement to check if the application object already exists and, if it does, don't run the ComObjActive("Word.Application") line; I simply stick with the COM object that is in use, which I've made global.

Thank you for your help! Have a fantastic day!

Post Reply

Return to “Ask for Help (v1)”