Warm tip: This article is reproduced from stackoverflow.com, please click
Anaconda excel python python-3.x vba

Pause Python3 code until excel macro is finished

发布于 2020-04-11 11:35:10

So, I have a very large excel workbook that is full of macros and I'm automating the use of this work book via python3 and pywin32. I was wondering if anyone knows how to pause the python script while the VBA macro runs?

Questioner
Tyler Burr
Viewed
107
Rodrigo Castilho 2020-02-05 23:35

Three ways I could suggest you approach this:

1. Use a file to signal Python that VBA has concluded its work

To do that, have your VBA script create a blank file (could be .xlsx)

import os.path
import time

"""
First block of code here
"""

while os.path.isfile('signal.xlsx') == False:
    time.sleep(10)

"""
Second block of code here
"""

2. Calculate how long it takes for your VBA script to run

If you're having your script alter some aspects of a worksheet, do a run with a shorter version, calculate how long it takes and then multiply the run time by the total iterations it will have to run through.

Have Python wait those many seconds before running the following blocks.

import time

time.sleep(seconds)

3. Use the Python Scheduler

You could also use the Schedule project to run your script at a given time if you think it's a safer play to run it during the evening, for instance.

I'd refer you to https://pypi.org/project/schedule/ as it has a very straight forward usage example.