简体   繁体   中英

Handling VBA popup message boxes in Microsoft Excel

I'm required to automate an Excel file with Python, the problem is that the Excel has macro in it , when clicking on a macro button it presents a popup:

宏截图

The popup message box itself has a button that I must click to proceed. I've tried with both Win32com and Win32 API libraries in Python but I was unable to find any solution in the documentation.

my code is as follows :

    ms_excel_app = win32.gencache.EnsureDispatch('Excel.Application')
    ms_excel_app.Visible = True
    ms_excel_app.DisplayAlerts = False

    template_file = r"C:\Templates_for_test\macro_test.xlsm"


    ms_excel_file =ms_excel_app.Workbooks.Open(template_file)
    ms_excel_file.DisplayAlerts = False
    excel_sheet = ms_excel_file.ActiveSheet
    # Opening a template file
    ms_excel_file = ms_excel_app.Workbooks.Open(template_file)

    spread_sheet = ms_excel_file.ActiveSheet

    # Click on 'Current date and time' macro button
    ms_excel_app.Application.Run("Sheet1.CommandButton1_Click")
    # TODO  verify verify timestamp and click ok- popup appears verify date and time format : dd/mm/yyyy hh:mm:ss
    timestamp_message = time.strftime("%d/%m/%Y %H:%M:%S")

what I'm trying to do is to identify the popup in the screenshot and click on the 'OK' button

A bit late, just post a solution since I faced the same case.

The message box gets Excel application stuck and accordingly blocks your main process. So, a general solution:

  • start a child thread to listen to the message box -> close it once found
  • do your main work with the Excel file
  • stop the child thread when everything is finished

As you're using pywin32 , it can also be used to catch and close message box. A Thread class to do the job:

# ButtonClicker.py

import time
from threading import Thread, Event
import win32gui, win32con


class ButtonClicker(Thread):

    def __init__(self, title:str, interval:int):
        Thread.__init__(self)
        self._title = title 
        self._interval = interval 
        self._stop_event = Event()   

    def stop(self):
        '''Stop thread.'''
        self._stop_event.set()

    @property
    def stopped(self):
        return self._stop_event.is_set()

    def run(self):
        while not self.stopped:
            try:
                time.sleep(self._interval)
                self._close_msgbox()
            except Exception as e:
                print(e, flush=True)

    def _close_msgbox(self):
        # find the top window by title
        hwnd = win32gui.FindWindow(None, self._title)
        if not hwnd: return

        # find child button
        h_btn = win32gui.FindWindowEx(hwnd, None,'Button', None)
        if not h_btn: return

        # show text
        text = win32gui.GetWindowText(h_btn)
        print(text)

        # click button        
        win32gui.PostMessage(h_btn, win32con.WM_LBUTTONDOWN, None, None)
        time.sleep(0.2)
        win32gui.PostMessage(h_btn, win32con.WM_LBUTTONUP, None, None)
        time.sleep(0.2)

Finally, your code may look like:

from ButtonClicker import ButtonClicker


# 1. start a child thread
# ButtonClicker instance tries to catch window with specified `title` at a user defined frequency. 
# In your case, the default title for Excel message box is `Microsoft Excel`.
listener = ButtonClicker("Microsoft Excel", 3)
listener.start()


# 2. do your work with Excel file as before
# though it might be blocked by message box, the concurrent child thread will close it

ms_excel_app = win32.gencache.EnsureDispatch('Excel.Application')
ms_excel_app.Visible = True
ms_excel_app.DisplayAlerts = False

template_file = r"C:\Templates_for_test\macro_test.xlsm"
...

# 3. close the child thread finally
listener.stop()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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