Ari Yxm
Ari Yxm

Reputation: 103

Run a Word VBA Macro with Python

I am trying to call a Word macro using Python. I tried to adopt the logic used to run Excel VBA Macros through Python (there are plenty of examples of how to run Excel Macros through python, but I did not find any for word). Here is the code I am trying to use. However, what I get is that Python keeps running forever and I don't know why. What am I doing wrong?

Here is my attempt:

import os
import comtypes.client

path=r"path to my folder containing file.docx"

word=comtypes.client.CreateObject("Word.Application")
docx=word.Documents.Open(path, ReadOnly=1)
docx=word.Application.Run("My_Macro_Name")
word.Documents(1).Close(SaveChanges=0)
word.Application.Quit()
wd=0

Also I have tried to specify better the position of my VBA Macro (I saved it in a .docm file), but still there is no result. Python keeps running without showing any result. Here is my attempt:

import os
import comtypes.client

path=r"path to the .docm file where I saved the vba macro"

word=comtypes.client.CreateObject("Word.Application")
word.Documents.Open(path,ReadOnly=1)
word.Run("Project.Modulo1.ConvertDoc")
word.Documents(1).Close(SaveChanges=0)
word.Application.Quit()
wd=0

Upvotes: 9

Views: 7052

Answers (1)

Binh Vo
Binh Vo

Reputation: 104

Why don't you run your VBA marco indirectly via Cscript/Wscript? You don't have to use comtypes package. Let's create a VBS file to run marco:

Set objExcel = CreateObject("Excel.Application")
Set objWorkbook = objExcel.Workbooks.Open("test.xls")

objExcel.Application.Visible = True
objExcel.Workbooks.Add
objExcel.Cells(1, 1).Value = "Test value"

objExcel.Application.Run "Macro.TestMacro()"
objExcel.ActiveWorkbook.Close


objExcel.Application.Quit
WScript.Echo "Finished."
WScript.Quit

BAT file:

C:\Windows\System32\cscript.exe D:\Script.vbs > output.log
exit

And now you can run a batch file from Python:

import subprocess
subprocess.call([r'path where the batch file is stored\name of the batch file.bat'])

You can read its response in output log file.

Upvotes: 1

Related Questions