Search code examples
pythonvbams-wordpywin32comtypes

Passing an argument from python script to Word Macro VBA (pywintypes.com_error: (-2147352567, 'Exception occurred.')


I have a Word Macro VBA script that inserts a docx file in a word document:

Public Sub Macro(path As String)
Selection.InsertFile FileName:=path, Range:="", ConfirmConversions:=False, Link:=True, Attachment:= False

ActiveDocument.Close_ SaveChanges:=wdSaveChanges, _ OriginalFormat:=wdOriginalDocumentFormat

Aplication.Quit SaveChanges:=wdSaveChanges

I would like to create a python script that calls the Macro and pass as an argument the path of the file which will be inserted in the VBA script.

import win32com.client as win32

word = win32.DispatchEx('Word.Application')
word.Visible = True

doc = word.Documents.Open(r'path to file .docx')
   
word.Application.Run("Complete.Macro.Name", "path_to_file_docx")

 

But I am getting the following error:

pywintypes.com_error: (-2147352567, 'Exception occurred.', (0, None, None, None, 0, -2147352567), None)

I read that if the Sub receives an argument the VBA is not a Macro anymore. Does anyone know how to overcome this?


Solution

  • Using

    import sys
    import pywintypes
    
    try:
        ...
    except pywintypes.com_error:
        sys.exit(1)
    

    Seems to solve the problem.