简体   繁体   English

暂停 Python3 代码直到 excel 宏完成

[英]Pause Python3 code until excel macro is finished

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.所以,我有一个非常大的 excel 工作簿,里面充满了宏,我正在通过 python3 和 pywin32 自动使用这本工作簿。 I was wondering if anyone knows how to pause the python script while the VBA macro runs?我想知道是否有人知道如何在 VBA 宏运行时暂停 python 脚本?

Three ways I could suggest you approach this:我可以建议你通过三种方式来解决这个问题:

1. Use a file to signal Python that VBA has concluded its work 1. 使用文件通知 Python VBA 已完成其工作

To do that, have your VBA script create a blank file (could be .xlsx)为此,让您的 VBA 脚本创建一个空白文件(可能是 .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 2.计算你的VBA脚本运行需要多长时间

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.在运行以下块之前让 Python 等待几秒钟。

import time

time.sleep(seconds)

3. Use the Python Scheduler 3. 使用 Python 调度器

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.例如,如果您认为在晚上运行脚本更安全,您还可以使用 Schedule 项目在给定时间运行脚本。

I'd refer you to https://pypi.org/project/schedule/ as it has a very straight forward usage example.我会向您推荐https://pypi.org/project/schedule/,因为它有一个非常简单的用法示例。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM