Home > Back-end >  Win32com: Close a specific Excel file if it's opened
Win32com: Close a specific Excel file if it's opened

Time:02-23

I just want to check if a specfic Excel file is open. If it is, I want to close only that file.

In the below code, using:

xl.Workbooks.Close()

closes all open Excel files.

Using:

xl.Workbooks.Close(FileName=xlPath)

leads to

TypeError: Close() got an unexpected keyword argument 'FileName'.

Complete code:

import win32com.client as w3c

xl=w3c.gencache.EnsureDispatch("Excel.Application")

my_workbook = "test.xlsx"
xlPath='C:/Desktop/test.xlsx'

if xl.Workbooks.Count > 0:
    if any(i.Name == my_workbook for i in xl.Workbooks):
        xl.Workbooks.Close(FileName=xlPath)

xl.Workbooks.Close()

CodePudding user response:

Per the Excel object library docs, Workbook.Close is a method of the Workbook object. Therefore, use the workbook object in your iteration which is i (renamed below to wb for clarity). Also, your any() expression will not capture i-th workbook in order to close. So run name check inside for-loop.

...
if xl.Workbooks.Count > 0: 
    for wb in xl.Workbooks:
        if wb.Name == my_workbook: 
            wb.Close()
  • Related