Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Call Microsoft Word VBA code from within Powershell

I have created a Microsoft Word 2010 macro using the Record Macro feature to search the document to find a certain string of words, and to insert those string of words into Excel.

I want to call this macro in Powershell.

Since the script lives in Microsoft Word, is it possible to reach into Word using Powershell and to execute these Macros or will I have to rewrite the macro in Powershell?

I want to run this Macro on several documents in a given folder.

like image 383
Nudo Avatar asked Mar 16 '26 12:03

Nudo


2 Answers

This do the trick:

$wd = new-object -comobject word.application # create a com object interface (word application)

$wd.documents.open("C:\word\test.doc") # open doc

$wd.run("Macro01") # exec macro named macro01

$wd.quit() # exit application

The macro must be saved on normal.dot (normal.dotm for 2010 and above) to have it in all open documents.

like image 162
CB. Avatar answered Mar 19 '26 02:03

CB.


I have this way of running a Word macro from PowerShell:

$WordFile = "Path to Your File.docx"
Start-Process winword.exe -ArgumentList ("/t", "`"$WordFile`"", "/mTheNameOfYourVBAScript") -Wait

According to my observations, this is faster than creating a Com-object

like image 30
Андрей Зорин Avatar answered Mar 19 '26 02:03

Андрей Зорин