Nudo
Nudo

Reputation: 81

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.

Upvotes: 3

Views: 6270

Answers (2)

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

Upvotes: 0

CB.
CB.

Reputation: 60928

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.

Upvotes: 5

Related Questions