Home » excel » excel – Problem with exiting a Word doc using Python

excel – Problem with exiting a Word doc using Python

Posted by: admin April 23, 2020 Leave a comment

Questions:

This is my first time using this so be kind 🙂 basically my question is I am making a program that opens many Microsoft Word 2007 docs and reads from a certain table in that document and writes that info to an excel file there is well in excess of 1000 word docs. I have all of this working but the only problem when I run my code it does not close MSword after opening each doc I have to manually do this at the end of the program run by opening word and selecting exit word option from the Home menu. Another problem is also if a run this program consecutively on the second run everything goes to hell it prints the same thing repeatedly no matter which doc is selected I think this may have to do with how MSword is deciding which doc is active e.g. is it still opening the last active document that was not closed from the last run. Anyways here is my code for the opening and closing part I wont bore you guys with the rest::

MSWord = win32com.client.Dispatch("Word.Application")
MSWord.Visible = 0
# Open a specific file
#myWordDoc = tkFileDialog.askopenfilename()
MSWord.Documents.Open("C:\Documents and Settings\fdosier" + chosen_doc)
#Get the textual content
docText = MSWord.Documents[0].Content
charText = MSWord.Documents[0].Characters
# Get a list of tables
ListTables = MSWord.Documents[0].Tables

------Main Code---------

MSWord.Documents.Close
MSWord.Documents.Quit
del MSWord
How to&Answers:

Basically, Python is not VBA, so this:

MSWord.Documents.Close

is equivalent to:

getattr(MSWord.Documents, "Close")

i.e. you just get some method object and do nothing with it. You need to call the method with the call operator (the parentheses 🙂 :

MSWord.Documents.Close()

Accordingly for .Quit.

Answer:

Before your MSWord.Quit did you try using:

MSWord.ActiveWindow.Close

Or even more simpley just doing

MSWord.Quit

I dont really understand if you are trying to close a document or the application.

Answer:

I think you need a MSWord.Quit at the end (before and/or instead of the the del)