1

I need to open an Excel sheet, refresh a pivot table, save it and close it. However, whenever I open an instance of Excel using python, no matter how hard I try, it stays open. I also want to use an already running instance, if there is one available and, if not, create one. Finally, if there was an instance running, just close the workbook and else, close Excel.

I've tried this solution to no avail. I also tried this one, but no success.

Here is the code. It does exactly what tis supposed to do, however, the Excel process remains running in the background. I can even call Application.Visible = True and it will pop up again.

import pywintypes
import pythoncom 
from win32com import client

pythoncom.CoInitialize()

try:
    Application = client.GetActiveObject("Excel.Application")
    Application.Visible = True
except pywintypes.com_error:
    Application = client.Dispatch("Excel.Application")
    Application.Visible = False

Workbook = Application.Workbooks.open('file_name.xlsx'))
Workbook.RefreshAll()
Workbook.Save()

if len(Application.Workbooks) == 1: # If there is only one workbook, close Excel
    Application.Quit()
else:
    Workbook.Close()

pythoncom.CoUninitialize()
  • 1
    Your ```If``` statement should be a ```While``` statement. Something like While greater than 1, close workbook, then quit Excel. – Brian Feb 12 '20 at 23:22
  • (Sledgehammer warning!) As a last resort, you can make a `subprocess` call and close (kill) Excel via the shell. Something like `taskkill /f /im Excel.exe`. Again, probably your last resort. – S3DEV Feb 12 '20 at 23:25

0 Answers0