ArtsAutosBooksBusinessEducationEntertainmentFamilyFashionFoodGamesGenderHealthHolidaysHomeHubPagesPersonal FinancePetsPoliticsReligionSportsTechnologyTravel
  • »
  • Technology»
  • Computers & Software»
  • Computer Science & Programming

AppleScript and Microsoft Word

Updated on October 6, 2017
AppleScripter profile image

Insanely obsessed with anything involving 'cracking the code', I am an AppleScript and Mac OS Aficionado. Self-taught for the most part, I h

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"
		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 .


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

AppleScript Coding for Beginners (AppleScript 1-2-3)

Apple Training Series: AppleScript 1-2-3 [APPLE TRAINING SERIES REVISED]
Apple Training Series: AppleScript 1-2-3 [APPLE TRAINING SERIES REVISED]

If you want to learn AppleScript from scratch, I highly recommend this guide. It is easy to follow, with tons of really useful example scripts. You'll want to read this book from cover to cover.


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.

Comments on AppleScript and Microsoft Word

    0 of 8192 characters used
    Post Comment

    • AppleScripter profile image

      AppleScripter 17 months ago

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

    • profile image

      ButcombePete 20 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?


    This website uses cookies

    As a user in the EEA, your approval is needed on a few things. To provide a better website experience, uses cookies (and other similar technologies) and may collect, process, and share personal data. Please choose which areas of our service you consent to our doing so.

    For more information on managing or withdrawing consents and how we handle data, visit our Privacy Policy at: ""

    Show Details
    HubPages Device IDThis is used to identify particular browsers or devices when the access the service, and is used for security reasons.
    LoginThis is necessary to sign in to the HubPages Service.
    Google RecaptchaThis is used to prevent bots and spam. (Privacy Policy)
    AkismetThis is used to detect comment spam. (Privacy Policy)
    HubPages Google AnalyticsThis is used to provide data on traffic to our website, all personally identifyable data is anonymized. (Privacy Policy)
    HubPages Traffic PixelThis is used to collect data on traffic to articles and other pages on our site. Unless you are signed in to a HubPages account, all personally identifiable information is anonymized.
    Amazon Web ServicesThis is a cloud services platform that we used to host our service. (Privacy Policy)
    CloudflareThis is a cloud CDN service that we use to efficiently deliver files required for our service to operate such as javascript, cascading style sheets, images, and videos. (Privacy Policy)
    Google Hosted LibrariesJavascript software libraries such as jQuery are loaded at endpoints on the or domains, for performance and efficiency reasons. (Privacy Policy)
    Google Custom SearchThis is feature allows you to search the site. (Privacy Policy)
    Google MapsSome articles have Google Maps embedded in them. (Privacy Policy)
    Google ChartsThis is used to display charts and graphs on articles and the author center. (Privacy Policy)
    Google AdSense Host APIThis service allows you to sign up for or associate a Google AdSense account with HubPages, so that you can earn money from ads on your articles. No data is shared unless you engage with this feature. (Privacy Policy)
    Google YouTubeSome articles have YouTube videos embedded in them. (Privacy Policy)
    VimeoSome articles have Vimeo videos embedded in them. (Privacy Policy)
    PaypalThis is used for a registered author who enrolls in the HubPages Earnings program and requests to be paid via PayPal. No data is shared with Paypal unless you engage with this feature. (Privacy Policy)
    Facebook LoginYou can use this to streamline signing up for, or signing in to your Hubpages account. No data is shared with Facebook unless you engage with this feature. (Privacy Policy)
    MavenThis supports the Maven widget and search functionality. (Privacy Policy)
    Google AdSenseThis is an ad network. (Privacy Policy)
    Google DoubleClickGoogle provides ad serving technology and runs an ad network. (Privacy Policy)
    Index ExchangeThis is an ad network. (Privacy Policy)
    SovrnThis is an ad network. (Privacy Policy)
    Facebook AdsThis is an ad network. (Privacy Policy)
    Amazon Unified Ad MarketplaceThis is an ad network. (Privacy Policy)
    AppNexusThis is an ad network. (Privacy Policy)
    OpenxThis is an ad network. (Privacy Policy)
    Rubicon ProjectThis is an ad network. (Privacy Policy)
    TripleLiftThis is an ad network. (Privacy Policy)
    Say MediaWe partner with Say Media to deliver ad campaigns on our sites. (Privacy Policy)
    Remarketing PixelsWe may use remarketing pixels from advertising networks such as Google AdWords, Bing Ads, and Facebook in order to advertise the HubPages Service to people that have visited our sites.
    Conversion Tracking PixelsWe may use conversion tracking pixels from advertising networks such as Google AdWords, Bing Ads, and Facebook in order to identify when an advertisement has successfully resulted in the desired action, such as signing up for the HubPages Service or publishing an article on the HubPages Service.
    Author Google AnalyticsThis is used to provide traffic data and reports to the authors of articles on the HubPages Service. (Privacy Policy)
    ComscoreComScore is a media measurement and analytics company providing marketing data and analytics to enterprises, media and advertising agencies, and publishers. Non-consent will result in ComScore only processing obfuscated personal data. (Privacy Policy)
    Amazon Tracking PixelSome articles display amazon products as part of the Amazon Affiliate program, this pixel provides traffic statistics for those products (Privacy Policy)