ElJuanito
ElJuanito

Reputation: 13

win32com.client.Dispatch('Excel.Application') has stopped working

I have a process that clicks an Export button with pyautogui, and then waits for the Excel file to automatically open. This can take anything up to 10 seconds, so I wrote a small function so it waits for the Excel file to open. The meat of the function was based on this little experiment:

from win32com.client import Dispatch

while True:
    xl = Dispatch('Excel.Application')
    print(len(xl.Workbooks))

When I first made this and ran it, it spat out a string of zeros until I opened an instance of Excel, and then it spat out a string of ones, and when I close Excel it spat out zeros again. It was exactly what I needed to build a function like this:

def export_report():
    """Click Export and wait 30 seconds for it to open."""
    xl = Dispatch('Excel.Application')
    open_workbooks_before_export = len(xl.Workbooks)
    click_image_on_screen('images/button_export_csv.png')
    wait = 0
    while len(xl.Workbooks) == open_workbooks_before_export: 
        xl = Dispatch('Excel.Application')
        if len(xl.Workbooks) != open_workbooks_before_export:
            break
        else:
            time.sleep(0.5)
            wait += 1
            if wait > 60:
                raise Exception('Report is not exporting')

Again, I'm sure when I first made this it worked perfectly. It just loops around waiting for the number of activate Excel workbooks to change, and then breaks out. But the next day it just stopped working. The previous snippet just spits out zeros, no matter how many instances of Excel I open. It's like the Dispatch('Excel.Application') part isn't working.

When I set xl.Visible=True a new, blank instance of Excel is launched, but that isn't what I want. It should access the running instance so I can access details of the currently open Excel files.

Any ideas why this has stopped working, and how I can get it to work again?

Upvotes: 0

Views: 533

Answers (0)

Related Questions