Computer_Nerd
Computer_Nerd

Reputation: 102

Python Interactions with Excel Macros

I would like to quit my Excel application from my Python code. My Python code opens an excel book, runs a macro, then closes the book. However, the Excel application is still running. How can I quit Excel?

This is the error I get from Python IDLE:

(-2147417848, 'The object invoked has disconnected from its clients.', None, None)

Here is my Python Code:

import xl


report = xl.Workbook(r"C:\Desktop\Reader.xlsm")
print(report)

report.xlWorkbook.Application.Run('Reader')

report.xlWorkbook.Close(SaveChanges=False)
report.xlWorkbook.Application.Quit()

print("The job is done")

Here is my Excel macro:

Public Sub Reader()

MsgBox ("Hello World")

End Sub

Upvotes: 0

Views: 1978

Answers (2)

QMCM
QMCM

Reputation: 31

Thanks, it helped when I had an issue with xlwings! I have connected your answer with this article: com_error: (-2147352567, 'Exception occurred.', (0, None, None, None, 0, -2147024809), None)

The above solution is for python 2. For python 3 it would look like:

import win32com.client

xl = win32com.client.Dispatch("Excel.Application")
filepath = *INSERTFILEPATHHERE* #for example "C:\Desktop\Reader.xlsm"
report = xl.Workbooks.Open(filepath) 
xl.Application.Run('Reader')
report.close() #empty brackets
xl.Application.quit()
xl = None
del xl

print("The job is done")

You may also use xlwings or openpyxl instead of win32com to process your files.

Upvotes: 1

Ricardo A
Ricardo A

Reputation: 1815

The comment from dwirony is a workaround that is definitely usable. However you really want to go the right way about this or you may end up with a hanged excel process and memory leaks.

In my opinion the correct way would be:

import win32com.client

xl = win32com.client.Dispatch("Excel.Application")

report = xl.Workbooks.Open("C:\Desktop\Reader.xlsm")
xl.Application.Run('Reader')
report.Close False
xl.Application.Quit()
xl = None
del xl

print("The job is done")

Upvotes: 3

Related Questions