AppleScript and Microsoft Word

The World of Word

One of the more popular apps today is Microsoft Word. Widely used on both Windows and MacOS platforms, still AppleScript support is rather scanty. What now seems to be the standard english-like language of AppleScript, is a bit more complex with Word as its AppleScript entries are based upon Microsoft's Visual Basic.


On this page I will go into depth on the deviation from the standard AppleScript syntax with Word and how to understand its constructs in order to effectively deal with those differences and write code that is maybe a little more like english syntax.

Creating a New Document with Microsoft Word 2004

An AppleScript to create a new text document with default text

For those of you who prefer to use Word for your text documents, this is a fairly straightforward script to create a new document with a default font and text and save it to your hard drive:

tell application "Microsoft Word"
	activate
	try
		set newDoc to make new document
		set name of font object of text object of newDoc to "Arial"
		--Here you could have a 'text returned of' dialog to set the text font for the new document to a font of your choice. Of course, the font would have to exist on the target hard drive.
		set documentName to text returned of (display dialog "Enter name for new document:" default answer "Untitled Document" with icon 1 buttons {"Cancel", "Save"} default button 2)
		save as newDoc file name documentName
		--By default, the document is created in the currently active folder.
		set initialText to text returned of (display dialog "Enter initial text for new document:" default answer "" with icon 1 buttons {"Cancel", "Insert"} default button 2)
		if initialText is not equal to "" then
			set documentRange to create range active document start 0 end 0
			insert text initialText at documentRange
		end if
		--If initialText has no value, then a text document is opened with no initial text.
	on error
		if documentName = "" then
			display dialog "Document creation aborted!" with icon 0 buttons "OK" default button 1
		end if
	end try
end tell

The else clause of the conditional above instructs AppleScript to ignore the fact that no initial text was requested for the new document and creates the document anyway. The value of 0 for start and end tells Word that it is a document that does not yet have any text or if there is existing text, to place it before the existing text .

Source

Formatting and Editing Text Objects with Word 2008

While Microsoft has its own scripting language (Visual Basic for Applications or 'VBA') to do all (most) of the same things as presented here, it is rather clunky and difficult to use compared with the more natural syntax of AppleScript.

Here we will look at some of the most necessary scripting elements for Word 2008 through a single document named 'MyText.doc'.

First creating and opening a new document:

tell application "Microsoft Word"
	set createDoc to make new document
	set name of font object of text object of createDoc to ¬
	"Lucida Grande"
	set size of font object of text object of createDoc to "14"
	save as createDoc file name "MyText.doc"
	open createDoc
end tell

'set createDoc to make new document' creates the new document and places a file reference to the new document into the variable createDoc.

Once that reference to the document is made, you can direct individual statements to the reference named createDoc or within a tell block:

tell createDoc

...

end tell

Now, let's look at a few ways that you can edit text in the document given this initial text:

It was a stormy day as I set out on my journey to learn how to write my first AppleScript with Microsoft Word 2008.

tell createDoc
	select word 4 of createDoc
	-- or select word 4 of active document
	set bold of font object of selection to true
	set content of text object of selection to "sunny"
end tell

This results in:

It was a sunny day as I set out on my journey to learn how to write my first AppleScript with Microsoft Word 2008.

The fourth word is selected, its font style set to bold, and its content changed to 'sunny'.
Note that changing styles of the selected text requires the use of the expression 'font object' and to replace the content with the word 'sunny' you must use 'text object'

Then to add text to the end of the document by way of a text entry dialog:

set appendText to text returned of (display dialog "Enter text to append to the end of this document:" default answer "" buttons {"Cancel", "Insert"} default button 2)
set appendText to (return & return & appendText)
insert text appendText at end of text object of active document

Editing Text Attributes in Microsoft Word

If you haven't done much with AppleScript and Microsoft Word, you'll immediately see below that Word is a sort of an odd-bird when it comes to scripting. You can tell that it was not originally meant to be scripted with AppleScript because the syntax is awkward and wordy. The reason is that Word was originally scripted in Visual Basic which is not as fluid and English-like as AppleScript and was adapted to AppleScript after the fact. With that said, here is a script that should give you a good handle on how to script word:

tell application "Microsoft Word"
set saveDelimiters to text item delimiters of AppleScript
set textRange to text object of active document
select textRange
set fontRange to font object of active document
set name of font object of textRange to "Helvetica"
set font size of font object of text object of active document to 14
set italic of font object of textRange to true
set bold of font object of textRange to true
set colorChoices to {"black", "blue", "turquoise", "bright green", "pink", "red", "yellow", "white", "dark blue", "teal", "green", "violet", "dark red", "dark yellow", "gray50", "gray25"}
set colorConversions to {black, blue, turquoise, bright green, pink, red, yellow, white, dark blue, teal, green, violet, dark red, dark yellow, gray50, gray25}
set newColor to choose from list colorChoices with prompt "Choose a new color for body text:" as Unicode text
set text item delimiters of AppleScript to ","
set x to 1
repeat with theColor in colorChoices
if newColor contains theColor then exit repeat
set x to x + 1
end repeat
set newColor to text item x of colorConversions
set color index of font object of textRange to newColor
set text item delimiters of AppleScript to saveDelimiters
end tell

The main thing to note about scripting Word is that it requires the use of a lot of references to objects to be stored in variable form in order to work in scripts. For instance:

set textRange to text object of active document
select textRange

Which, in AppleWorks 6, can be stated more simply:

select every text

Another thing to note is my use of the lists colorChoices and colorConversions

The first is necessary to put the color choices into a suitable form for choose from list. The second is for comparison to get the chosen color in a form that will work with the syntax for the script line set color index of font object of textRange to newColor which cannot be in string form since Word expects a color value instead. Incidentally, the colors gray50 and gray25 are two different shades of gray.

AppleScript for Noobs

More by this Author

  • AppleScript and FileMaker
    4

    Learning How to Write FileMaker Pro Scripts for Beginners. Free AppleScripts for those who are new. Many scripts are a mix of AppleScript and FileMaker.

  • More Advanced AppleScript Code
    0

    For those of you who still cannot get enough AppleScript to feed your fix, some more free applescript code,Finder,Microsoft Word,Pages,AppleWorks,PowerPoint,TextEdit,iTunes,POSIX paths,database events

  • Free AppleScript Code Examples
    1

    Write AppleScript Code,free AppleScripts of display dialog,display alert,choose from list,finder,choose file,choose file name,choose folder,choose application,choose color,Finder,TextEdit


Comments on AppleScript and Microsoft Word 2 comments

AppleScripter profile image

AppleScripter 4 days ago Author

Could you show me some of your code that you have tried so that I can better understand what you are trying to accomplish ?


ButcombePete 3 months ago

very helpful apple scripting pages thanks

I have a filemaker db from which I wish to construct letters using word for mac - I need to be able to use the flexibility of word as a word processor - I have managed after many trials and tribulations to write filemaker script that invokes applescripts to insert items at bookmarks in template word documents - however with multiple documents and multiple bookmarks in each document, it's very easy for a piece of applescript to go wrong and then difficult to debug it from within filemaker.

Do you have any other suggestions - you've clearly got much more experience with applescript than I?

    Sign in or sign up and post using a HubPages Network account.

    0 of 8192 characters used
    Post Comment

    No HTML is allowed in comments, but URLs will be hyperlinked. Comments are not for promoting your articles or other sites.


    Click to Rate This Article
    working