I am trying to write a Python script that will access and modify the active Excel workbook using the Excel COM interface. However, I am having difficulty getting this to work when there are multiple Excel instances running. For example, the code
import win32com.client
xl = win32com.client.Dispatch("Excel.Application")
print(xl.ActiveWorkbook.FullName)
prints out the name of the active workbook from the first running instance of Excel only. What I really want is the workbook that I last clicked on, regardless of what Excel instance it was in.
Thanks.
EDIT FOR COMMENTS
There might be a better way to do this.
Install the excellent psutil
Now enumerate the windows, but get the window title and pid.
Now just find the first pid that is in our excelPids
END EDITS
There is a number of things to take into consideration here:
Does one instance have multiple workbooks open? In this case
Will indeed give you the last active workbook.
Or are there separate instances of EXCEL.EXE running? You can get each instance with:
But this defeats the purpose because you need to know the name AND this will not tell you which one last had focus.
To @tgrays comment above, if your excel instance is guaranteed to be the foreground window then:
But worst case scenerio, multiple instances and you have to find which had focus last, you'll have to enumerate all the windows and find the one you care about:
Good luck with this one!