Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to have python wait until an Excel Macro/Refresh is done

I am using Python to run a macro in excel. and I want Python to close excel. The macro refreshes a data connection in excel which can be slow.

How do I have python wait until the refresh is done to close. This is what I am using, I need something before the xl.Quit that will wait until the refresh in macro is done????

 import win32com.client
 import os

 xl = win32com.client.DispatchEx("Excel.Application")
 wb = xl.workbooks.open("X:\Backoffice\Options Trading\BloombergRate.xlsm")
 xl.Visible = True
 xl.run("Refresh")
 xl.Quit()

Wait ways can I make this work?

like image 440
Trying_hard Avatar asked Apr 30 '26 12:04

Trying_hard


2 Answers

Edit your Refresh macro to set QueryTable.BackgroundQuery property to False. This should cause the macro to block until it is done.

like image 116
Steven Rumbalski Avatar answered May 03 '26 03:05

Steven Rumbalski


You don't even have to set up a macro to run this. win32com has a native method to refresh all data connections.

import win32com.client
import os

xl = win32com.client.DispatchEx("Excel.Application")
wb = xl.workbooks.open("X:\Backoffice\Options Trading\BloombergRate.xlsm")
xl.Visible = True
wb.RefreshAll()
xl.Quit()
like image 36
Yeqing Zhang Avatar answered May 03 '26 02:05

Yeqing Zhang