hey guys, I need help considering win32com in Python:
I have a routine that opens a Workbook, creates a sheet and puts some data on it.
If everything runs fine the woorkbook is saved and closed – If not the python session is terminated but the woorkbook is left open. So the reference is lost. Now when restarting the code Excel prompts you with the msg “workbook still open do you want to re-open?”.
So what I want is to suppress this msg. I found a solution that works for me when python terminates before writing to the sheet:
open_copys = self.xlApp.Workbooks.Count
if open_copys > 0:
""" Check if any copy is the desired one"""
for i in range(0, open_copys):
if(self.xlApp.Workbooks[i].FullName == self.file_path):
self.xlBook = self.xlApp.Workbooks[i]
else:
self.xlBook = self.xlApp.Workbooks.Open(self.file_path)
But if any changes were made on the EXCEL sheet this method is obsolet.
Anyone got an ides how to get back a reference to an open and changed worksheet from a new python session?
thx
Have you tried to remove all references to your COM objects before terminating the Python interpreter ? You can force them to be garbage collected (using gc.collect()) to be really sure they are gone. This way the workbook shouldn’t remain open in memory and you won’t have the error message.
Try adding a “close()” method to your class, with something like the following, and call it before the end of your script.