6

Whats wrong with this code? Why win32com.client.constants doesn't have attribute wdWindowStateMinimize?

>>> import win32com.client
>>> w=win32com.client.Dispatch("Word.Application")
>>> w.WindowState = win32com.client.constants.wdWindowStateMinimize
Traceback (most recent call last):
  File "<pyshell#2>", line 1, in <module>
    w.WindowState = win32com.client.constants.wdWindowStateMinimize
  File "C:\Python34\lib\site-packages\win32com\client\__init__.py", line 170, in __getattr__
    raise AttributeError(a)
AttributeError: wdWindowStateMinimize`
Oliver
  • 27,510
  • 9
  • 72
  • 103
ssssergey
  • 253
  • 1
  • 5
  • 9

1 Answers1

5

You must use EnsureDispatch instead:

>>> w=win32com.client.gencache.EnsureDispatch('Word.Application')
>>> win32com.client.constants.wdWindowStateMinimize
2
>>>

Note that the first time you use EnsureDispatch on a particular COM server, pywin32 generates the COM type lib for it (Word in your case), so it can take many seconds. For Excel, it took almost 30 seconds. But after that, the dispatch is quick, and you can even use the regular Dispatch (so you could code your app to use Dispatch, which is faster than EnsureDispatch, and check if the constant is defined, and if not, the code uses EnsureDispatch).

See my answer to this other post for more details.

Community
  • 1
  • 1
Oliver
  • 27,510
  • 9
  • 72
  • 103
  • Hi, now I have a problem with sharing my program with other users. The program is turned to exe-format with cx_Freeze module. It works perfectly on my PC, but raises error on others. Can you give me some advise, please? – ssssergey Feb 07 '15 at 09:06
  • @ssssergey Please post a separate question. – Oliver Feb 07 '15 at 13:40
  • Note that you don't need to `import win32com.client.constants` -- this gives an `ImportError`. – ivan_pozdeev Nov 16 '18 at 00:46
  • 1
    For my case in 2021, replace `win32com.client.Dispatch("Excel.Application")` by `win32com.client.gencache.EnsureDispatch("Excel.Application")` solved my problem of `AttributeError` – etoricky Jan 27 '21 at 07:31