Trying_hard Trying_hard - 2 months ago 20
Python Question

python Win32 Save

I am using python to open an excel file and make some changes and then I need to save it. I can get everything done except the save part. How do I get python to save the file. If I save it manual I get the pop up box and I can click save, but I don't want to have to manually click save. I want python to just save it and close excel. I need help, this is what I have. but it won't work. I can get it to save but not close????

import win32com.client
import os


xl = win32com.client.DispatchEx("Excel.Application")
xl.workbooks.open("C:\file.xlsm")
xl.run("file.xlsm!macro")
xl.Visible = True
xl.save = true
xl.close

Answer

You need to get a hook to the workbook object and apply the save as an argument to the close method:

xl = win32com.client.DispatchEx("Excel.Application")
wb = xl.workbooks.open("C:\file.xlsm")
xl.run("file.xlsm!macro")
xl.Visible = True
wb.Close(savechanges=1)
xl.Quit()
Comments