Syed Umar AnisCommand LineAutomate Microsoft Word on MacOS
Syed Umar AnisCommand LineAutomate Microsoft Word on MacOS
Command Line

Automate Microsoft Word on MacOS

Microsoft Word can be automated using AppleScript. For instance, the following script is going the open a new Word file.

osascript -e 'tell application "Microsoft Word" to create new document'

It goes further than that, we can open an existing document and save it as HTML.

tell application "Microsoft Word"
    open "path/to/your/document.docx"
    save as active document file name "path/to/save/document.html" file format format HTML
    close active document
end tell

But AppleScript doesn’t let us access all the functionality in the Word application and it can be painful to find help on what’s available. That’s where VBA macros come in. It enables us to automate almost every aspect of the application and has excellent reference docs.

We can get AppleScript to launch the application, trigger a macro and have VBA Macros do the automation inside the application. Here is AppleScript doing the same:

#!/usr/bin/osascript

-- Applescript to run a macro in Microsoft Word
-- First create the macro in the word document, before running this file
-- Usage: ./myScript.scpt <file path>
on run argv
	set filePath to (item 1 of argv) as string
	tell application "Microsoft Word"
		activate
		open filePath
		set theActiveDoc to the active document
		set macroName to "MyMacro"
		tell theActiveDoc
			run VB macro macro name macroName
		end tell
		close active document
	end tell
end run

Before running the above script we have to create the macro in MS Word. Go to Tools -> Macros to launch the VBA editor.

Hi, I’m Umar

Leave a Reply

Your email address will not be published. Required fields are marked *