0

i am trying to focus to excel file using win32com.client.

what i want is:

(1) simply return workbook instance when a given excel file is already opened.

(2) if that excel file is not opened yet >> open the excel file and then return workbook instance.

i am struggling because i don't know the difference between the methods getactiveobject & dispatch and so on...

in many cases, an error occurs >> (-2147352567 .......

can anyone make the code that i want?

this is a part of my code

'''
import win32com.client
xlsApp=win32com.client.GetActiveObject("Excel.Application")
myWB=xlsApp.Workbooks(workbook_name) 
'''
  • Welcome to StackOverflow! Can you [fix the markdown](https://stackoverflow.com/editing-help) in your post? It will help other's see the question more clearly. :) – tony May 26 '22 at 13:39

1 Answers1

0

I've done this before this is how I did it

import pygetwindow as gw
import pywinauto

def focus_to_window(window_title=None): 
     window = gw.getWindowsWithTitle(window_title)[0] 
     if window.isActive == False: 
         try: 
             pywinauto.application.Application().connect(handle=window._hWnd).top_window().set_focus() 
         except: 
             print('No permission')

That function requires you to pass in a window title, it does not have to be exact name for example if you have Discord named Discord #general you just need to put Discord because no matter where you go Discord string will always be in there

Also the reason why it prints No permission because some applications requires it to run as Admin

Damien
  • 61
  • 5
  • thank you for your help, but this is not i wanted.... not just focus to window, i need to get(return) excel instance to do something with win32com – YoungJoo Park May 26 '22 at 08:15
  • Sorry I might've misunderstood. But maybe this might help https://stackoverflow.com/questions/39877278/python-open-excel-workbook-using-win32-com-api – Damien May 26 '22 at 08:20