none
Python win32com Show VBA UserForm RRS feed

  • Question

  • I'm trying to control Word 2016 using a Python3 script using win32com. I've imported a VBA UserForm, and am trying to show it but receiving an error. Some Python code:

    from win32com.client.dynamic import Dispatch
    from win32com.client.dynamic import ERRORS_BAD_CONTEXT
    import win32com.client as win32
    
    app = win32.gencache.EnsureDispatch('Word.Application')
    app.Visible = True
    app.Documents.Open('.../'+current_doc+'.docx')
    
    try:    
      
     app.VBE.VBProjects(1).VBComponents.Import('.../UserForm1.frm')
        app.Run('UserForm_Initialize()')

    The script succesfully imports the UserForm, but upon attempting to initialize, it is throwing this error:

    com_error: (-2147352567, 'Exception occurred.', (0, 'Forms.Form.1', "Can't move focus to the control because it is invisible, not enabled, or of a type that does not accept the focus.", 'fm20.hlp', 0, -2147352573), None)

    Does anyone know a way to initialize the UserForm successfully? Why won't it let me initialize the UserForm in this way?

    Thanks!!!

    Note: I've verified the app.Run() command is correct by also separately importing a module to call the UserForm, and running it. Same error. However, if I then open the VBA console and run the same module, it successfully opens the UserForm.

    Tuesday, October 9, 2018 6:05 PM

All replies

  • Hi SpennyEco,

    According to my search, I assume that the error that you get is because the document you wanted to call from Word did not match the name you was referencing in your python code or it maybe a path error.

    First, you can use the code below to get more information about that error:

    import win32api
    e_msg = win32api.FormatMessage(-2147352565)
    print e_msg.decode('CP1251')


    For more information, please review the following links:

    pywintypes.com_error in Python during Excel import

    pywintypes.com_error opening Excel with Python

    Hopefully it helps you.

    Best Regards,

    Yuki


    MSDN Community Support Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread.

    Wednesday, October 10, 2018 6:42 AM
    Moderator
  • Hi SpennyEco,

    Thanks for your asking. Did you resolve your issue? If the post helps you, you can mark it as answer and close the post.

    Thank you for understanding. If you have any question, or update, please feel free to let us know.

    I wish you a happy life!

    Best Regards,

    Yuki

    MSDN Community Support Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread.

    Monday, October 15, 2018 7:22 AM
    Moderator