TweetFollow Us on Twitter

Introduction to Scripting Microsoft Word

Volume Number: 23 (2007)
Issue Number: 01
Column Tag: Applescript Essentials

Introduction to Scripting Microsoft Word

by Benjamin S. Waldie

Lately, there has been a lot of talk in the Macintosh community about Microsoft, and the forthcoming Office 12. One of Microsoft's big announcements is that they will be doing away with support for creating and running Visual Basic macros in the next version of Office. This leaves many people wondering how they will go about automating their Office applications. AppleScript to the rescue. I'm pleased to say that Entourage, Excel, PowerPoint, and Word are all AppleScriptable.

Office has supported AppleScript for some time now, and with the release of Office 11 in 2004, Microsoft actually completely re-implemented much of their AppleScript support, and also added AppleScript support for PowerPoint. Due to these changes, much of the AppleScript terminology in Word and Excel changed from previous versions. If you are currently using Office AppleScripts with a pre-2004 version of Office, then please be aware that you will probably need to make some modifications to your scripts when you decide to upgrade your Office suite. Of course, this should go without saying when upgrading any scriptable application. Any time any application is updated, AppleScript terminology changes may be introduced. This is why it is always a good idea to test your existing scripts with any new application version before implementing it into your live workflow.

This month, we're going to take a look at scripting Microsoft Word. We'll walk through some basic techniques for interacting with Word documents, and the content within those documents. Please note that all code in this month's column was written for and tested with Office 11 (2004). Therefore, if you're using a different version of Office, please be aware that the terminology you need to use may differ from that which I have used.

Working with Documents

Making a Document

Making a new Word document is relatively straightforward. To make a new Word document, simply use the make command, as demonstrated here.

tell application "Microsoft Word"
   make new document
end tell
--> document "Document1" of application "Microsoft Word"

Notice that the result of the make command is a reference to the newly created document. This reference may be placed into a variable, if desired, for future reference in your script.

Closing a Document

Closing a Word document is also pretty straightforward. To close a Word document, use the close command. Optionally, you may specify a constant value (yes, no, or ask) for the close command's saving parameter, to indicate whether the document being closed should be saved. The following example code will close a document without saving it.

tell application "Microsoft Word"
   close document 1 saving no
end tell

Opening a Document

To open a Word document, use the open command, followed by a reference to the document file you wish to open. The following example code will prompt the user to select a Word document file. It will then open that file.

set theDocFile to choose file with prompt "Please select a Word document file:"
tell application "Microsoft Word"
   open theDocFile
end tell

Please note that, in the example above, no result is returned by the open command. Since you will typically want your script to perform additional tasks on the newly opened document, you will need a way of referencing the document. There are a number of ways that this can be done. Assuming you know the name of the document, one way to do this is to retrieve a reference to the document using its name. For example:

set theDocFile to choose file with prompt "Please select a Word document file:"
set theDocName to name of (info for theDocFile)
tell application "Microsoft Word"
   open theDocFile
   set theDocument to document theDocName
end tell
--> document "My Document.doc" of application "Microsoft Word"

If you're sure that the target document will be in the front, then another way you can reference it is by referencing the active document application property. For example:

set theDocFile to choose file with prompt "Please select a Word document file:"
tell application "Microsoft Word"
   open theDocFile
   set theDocument to active document
end tell
--> active document of application "Microsoft Word"

Take note that the result of the code above is a reference to the active document. This may work fine in most cases. However, be aware that, since it is not referencing a specific document, if another document is brought to the front, then the incorrect document may be targeted.

It's also important to note is that, in Word, documents have an index number. However, this number does not indicate the front to back position of the document, as it often does in many other applications. Instead, it indicates the document's position, in the order that the documents were opened. In other words, if a document in the back was the last document to be opened, then the front document will not be document 1. For this reason, when you want to target the front document in Word, it's always good practice to reference the active document.

We have discussed a couple of ways to retrieve a reference to a newly opened document. There are others, some of which are more robust, and I would encourage you to see if you can come up with some ways of doing this on your own.

Saving a Document

Saving a previously saved document into its original location is as simple as using the save command, as demonstrated here.

tell application "Microsoft Word"
   save active document
end tell

However, suppose you want to save a document into a specific location, or in a different format? This is done using Word's save as command. This command has several optional parameters, which will allow you to specify the output location, format, and more. To save a document into a specific location, make use of the file name parameter, as follows:

set theOutputPath to (path to desktop folder as string) & "My Saved Doc.doc"
tell application "Microsoft Word"
   save as active document file name theOutputPath
end tell

To specify a format for the saved document, use the file format parameter. For example, the following code will save a document in RTF format:

set theOutputPath to (path to desktop folder as string) & "My Saved Doc.rtf"
tell application "Microsoft Word"
   save as active document file name theOutputPath file format format rtf
end tell

There are numerous other formats in which you can save a Word document, including Word template, HTML, web archive, and more. A complete list of supported formats can be found in Word's AppleScript dictionary, under the save as command.

Working with Document Text

Working with Text Ranges

In a Word document, text is typically referenced using text ranges. A text range is a class of object that refers to a specific area of text, such as a single character, word, or paragraph, or all of the text within the document. Each text range has a starting and ending position. For example, a text range might represent character 1 through character 5 of the document. The position 0 represents the absolute beginning of a document, just before the first character, so if you wanted to reference the first 5 characters of a document, the text range would actually begin at position 0, and end at position 5.

To reference text within a Word document, you must first create a text range. This is done by using the create range command. This command simply creates a reference for you, to the specified text content. Here's an example:

tell application "Microsoft Word"
   tell active document
      set theRange to create range start 0 end 5
   end tell
end tell
--> text range id «data iWrg0000000000000005» ¬
of active document of application "Microsoft Word"

The result of the code above is a reference to a range of text within my document, in this case, characters 1 through 5. I can now access attributes of this text by referencing the range. For example, the following code will get the text content within the range:

tell application "Microsoft Word"
   tell active document
      set theRange to create range start 0 end 5
      content of theRange
   end tell
end tell
--> "APPLE"

Getting the Entire Content of a Document

In Word, the document class possesses a text object property. This property references a text range representing the entire content of the document. For example:

tell application "Microsoft Word"
   tell active document
      content of text object
   end tell
end tell
--> "APPLESCRIPT ESSENTIALS
      Introduction to Scripting Microsoft Word
      Copyright 2007 by Ben Waldie...

Adding Text to a Document

To replace text in a Word document, create a text range representing the text to be replaced. Then set the content property of that range to the desired text. For example:

tell application "Microsoft Word"
   tell active document
      set theRange to create range start 0 end 5
      set content of theRange to "TEST"
   end tell
end tell

Another way that text can be added to a document is by inserting it. This is done by using the insert command. This command has a required parameter, text, which indicates the text to be inserted. It also has an optional parameter, at, which can be used to indicate the location before which the text should be inserted. For example, the following code will insert the text TEST at the beginning of the active document.

tell application "Microsoft Word"
   tell active document
      set theRange to create range start 0 end 0
      insert text "TEST" at theRange
   end tell
end tell

This same task could also have been accomplished by setting the content property of a range representing the beginning of the document to the specified text. For example:

tell application "Microsoft Word"
   tell active document
      set theRange to create range start 0 end 0
      set content of theRange to "TEST"
   end tell
end tell

Working with Other Content

It's also possible to add other types of elements besides text into Word documents via scripting. For example, you might want to insert a hyperlink, or an image.

Adding a Hyperlink to a Document

To add a hyperlink to a document, use the make command to create a hyperlink object. In doing so, you may specify property values for the hyperlink, including the text to be displayed the link URL, and the text range representing the location where the hyperlink should be created. For example, the following code will create a hyperlink to my company's website at the beginning of the active document.

tell application "Microsoft Word"
   tell active document
      set theRange to create range start 0 end 0
      make new hyperlink object at end with properties ¬
{text to display:"Automated Workflows, LLC", hyperlink ¬
address:"http://www.automatedworkflows.com", ¬
text object:theRange} end tell end tell --> hyperlink object "http://www.automatedworkflows.com" ¬
of active document of application "Microsoft Word"

Adding a Picture to a Document

Adding an inline picture to a document is similar to adding a hyperlink. Again, use the make command, but this time create an inline picture, rather than a hyperlink object. When using this command, you may specify property values for the picture, including the file name property, which should include the path of the picture file to be inserted (as a string). For example, the following code will create a new inline picture at the beginning of the active document.

set thePicturePath to choose file with prompt "Please select a picture to insert:"
tell application "Microsoft Word"
   tell active document
      set theRange to create range start 0 end 0
      make new inline picture at theRange with properties ¬ 
{file name:thePicturePath as string} end tell end tell --> inline picture 1 of text range id ¬
«data iWrg0000000000000000» of document "Document1" ¬
of application "Microsoft Word"

In Closing

Now that we have discussed some basic interaction with Word, where do you go from here? We have really only scratched the surface, and there's a lot more that can be done. Take some time to explore modifying attributes of text, such as the font, point size, and color. Explore modifying document properties, adjusting header and footer content, inserting a table of contents, and much more. Take some time to explore Word's AppleScript dictionary. You will find that it contains quite a lot of terminology, so it may actually take some time to become familiar and comfortable with it.

For additional help getting started with Word, be sure to review the Microsoft Word 2004 AppleScript Reference documentation. This documentation can be obtained in the Resources > Development Center > AppleScript Resources for Office 2004 section of Microsoft's Mactopia website at http://www.microsoft.com/mac/. You may also want to explore MacScripter.net's ScriptBuilders, at http://scriptbuilders.net/, where you will find some AppleScripts for Microsoft Word, some of which may even be editable!

Until next time, keep scripting!


Ben Waldie is the author of the best selling books "AppleScripting the Finder" and the "Mac OS X Technology Guide to Automator", available from http://www.spiderworks.com, as well as an AppleScript Training CD, available from http://www.vtc.com. Ben is also president of Automated Workflows, LLC, a company specializing in AppleScript and workflow automation consulting. For years, Ben has developed professional AppleScript-based solutions for businesses including Adobe, Apple, NASA, PC World, and TV Guide. For more information about Ben, please visit http://www.automatedworkflows.com, or email Ben at ben@automatedworkflows.com.

 

Community Search:
MacTech Search:

Software Updates via MacUpdate

Tor Browser 12.5.5 - Anonymize Web brows...
Using Tor Browser you can protect yourself against tracking, surveillance, and censorship. Tor was originally designed, implemented, and deployed as a third-generation onion-routing project of the U.... Read more
Malwarebytes 4.21.9.5141 - Adware remova...
Malwarebytes (was AdwareMedic) helps you get your Mac experience back. Malwarebytes scans for and removes code that degrades system performance or attacks your system. Making your Mac once again your... Read more
TinkerTool 9.5 - Expanded preference set...
TinkerTool is an application that gives you access to additional preference settings Apple has built into Mac OS X. This allows to activate hidden features in the operating system and in some of the... Read more
Paragon NTFS 15.11.839 - Provides full r...
Paragon NTFS breaks down the barriers between Windows and macOS. Paragon NTFS effectively solves the communication problems between the Mac system and NTFS. Write, edit, copy, move, delete files on... Read more
Apple Safari 17 - Apple's Web brows...
Apple Safari is Apple's web browser that comes bundled with the most recent macOS. Safari is faster and more energy efficient than other browsers, so sites are more responsive and your notebook... Read more
Firefox 118.0 - Fast, safe Web browser.
Firefox offers a fast, safe Web browsing experience. Browse quickly, securely, and effortlessly. With its industry-leading features, Firefox is the choice of Web development professionals and casual... Read more
ClamXAV 3.6.1 - Virus checker based on C...
ClamXAV is a popular virus checker for OS X. Time to take control ClamXAV keeps threats at bay and puts you firmly in charge of your Mac’s security. Scan a specific file or your entire hard drive.... Read more
SuperDuper! 3.8 - Advanced disk cloning/...
SuperDuper! is an advanced, yet easy to use disk copying program. It can, of course, make a straight copy, or "clone" - useful when you want to move all your data from one machine to another, or do a... Read more
Alfred 5.1.3 - Quick launcher for apps a...
Alfred is an award-winning productivity application for OS X. Alfred saves you time when you search for files online or on your Mac. Be more productive with hotkeys, keywords, and file actions at... Read more
Sketch 98.3 - Design app for UX/UI for i...
Sketch is an innovative and fresh look at vector drawing. Its intentionally minimalist design is based upon a drawing space of unlimited size and layers, free of palettes, panels, menus, windows, and... Read more

Latest Forum Discussions

See All

Listener Emails and the iPhone 15! – The...
In this week’s episode of The TouchArcade Show we finally get to a backlog of emails that have been hanging out in our inbox for, oh, about a month or so. We love getting emails as they always lead to interesting discussion about a variety of topics... | Read more »
TouchArcade Game of the Week: ‘Cypher 00...
This doesn’t happen too often, but occasionally there will be an Apple Arcade game that I adore so much I just have to pick it as the Game of the Week. Well, here we are, and Cypher 007 is one of those games. The big key point here is that Cypher... | Read more »
SwitchArcade Round-Up: ‘EA Sports FC 24’...
Hello gentle readers, and welcome to the SwitchArcade Round-Up for September 29th, 2023. In today’s article, we’ve got a ton of news to go over. Just a lot going on today, I suppose. After that, there are quite a few new releases to look at... | Read more »
‘Storyteller’ Mobile Review – Perfect fo...
I first played Daniel Benmergui’s Storyteller (Free) through its Nintendo Switch and Steam releases. Read my original review of it here. Since then, a lot of friends who played the game enjoyed it, but thought it was overpriced given the short... | Read more »
An Interview with the Legendary Yu Suzuk...
One of the cool things about my job is that every once in a while, I get to talk to the people behind the games. It’s always a pleasure. Well, today we have a really special one for you, dear friends. Mr. Yu Suzuki of Ys Net, the force behind such... | Read more »
New ‘Marvel Snap’ Update Has Balance Adj...
As we wait for the information on the new season to drop, we shall have to content ourselves with looking at the latest update to Marvel Snap (Free). It’s just a balance update, but it makes some very big changes that combined with the arrival of... | Read more »
‘Honkai Star Rail’ Version 1.4 Update Re...
At Sony’s recently-aired presentation, HoYoverse announced the Honkai Star Rail (Free) PS5 release date. Most people speculated that the next major update would arrive alongside the PS5 release. | Read more »
‘Omniheroes’ Major Update “Tide’s Cadenc...
What secrets do the depths of the sea hold? Omniheroes is revealing the mysteries of the deep with its latest “Tide’s Cadence" update, where you can look forward to scoring a free Valkyrie and limited skin among other login rewards like the 2nd... | Read more »
Recruit yourself some run-and-gun royalt...
It is always nice to see the return of a series that has lost a bit of its global staying power, and thanks to Lilith Games' latest collaboration, Warpath will be playing host the the run-and-gun legend that is Metal Slug 3. [Read more] | Read more »
‘The Elder Scrolls: Castles’ Is Availabl...
Back when Fallout Shelter (Free) released on mobile, and eventually hit consoles and PC, I didn’t think it would lead to something similar for The Elder Scrolls, but here we are. The Elder Scrolls: Castles is a new simulation game from Bethesda... | Read more »

Price Scanner via MacPrices.net

Clearance M1 Max Mac Studio available today a...
Apple has clearance M1 Max Mac Studios available in their Certified Refurbished store for $270 off original MSRP. Each Mac Studio comes with Apple’s one-year warranty, and shipping is free: – Mac... Read more
Apple continues to offer 24-inch iMacs for up...
Apple has a full range of 24-inch M1 iMacs available today in their Certified Refurbished store. Models are available starting at only $1099 and range up to $260 off original MSRP. Each iMac is in... Read more
Final weekend for Apple’s 2023 Back to School...
This is the final weekend for Apple’s Back to School Promotion 2023. It remains active until Monday, October 2nd. Education customers receive a free $150 Apple Gift Card with the purchase of a new... Read more
Apple drops prices on refurbished 13-inch M2...
Apple has dropped prices on standard-configuration 13″ M2 MacBook Pros, Certified Refurbished, to as low as $1099 and ranging up to $230 off MSRP. These are the cheapest 13″ M2 MacBook Pros for sale... Read more
14-inch M2 Max MacBook Pro on sale for $300 o...
B&H Photo has the Space Gray 14″ 30-Core GPU M2 Max MacBook Pro in stock and on sale today for $2799 including free 1-2 day shipping. Their price is $300 off Apple’s MSRP, and it’s the lowest... Read more
Apple is now selling Certified Refurbished M2...
Apple has added a full line of standard-configuration M2 Max and M2 Ultra Mac Studios available in their Certified Refurbished section starting at only $1699 and ranging up to $600 off MSRP. Each Mac... Read more
New sale: 13-inch M2 MacBook Airs starting at...
B&H Photo has 13″ MacBook Airs with M2 CPUs in stock today and on sale for $200 off Apple’s MSRP with prices available starting at only $899. Free 1-2 day delivery is available to most US... Read more
Apple has all 15-inch M2 MacBook Airs in stoc...
Apple has Certified Refurbished 15″ M2 MacBook Airs in stock today starting at only $1099 and ranging up to $230 off MSRP. These are the cheapest M2-powered 15″ MacBook Airs for sale today at Apple.... Read more
In stock: Clearance M1 Ultra Mac Studios for...
Apple has clearance M1 Ultra Mac Studios available in their Certified Refurbished store for $540 off original MSRP. Each Mac Studio comes with Apple’s one-year warranty, and shipping is free: – Mac... Read more
Back on sale: Apple’s M2 Mac minis for $100 o...
B&H Photo has Apple’s M2-powered Mac minis back in stock and on sale today for $100 off MSRP. Free 1-2 day shipping is available for most US addresses: – Mac mini M2/256GB SSD: $499, save $100 –... Read more

Jobs Board

Licensed Dental Hygienist - *Apple* River -...
Park Dental Apple River in Somerset, WI is seeking a compassionate, professional Dental Hygienist to join our team-oriented practice. COMPETITIVE PAY AND SIGN-ON Read more
Sublease Associate Optometrist- *Apple* Val...
Sublease Associate Optometrist- Apple Valley, CA- Target Optical Date: Sep 30, 2023 Brand: Target Optical Location: Apple Valley, CA, US, 92307 **Requisition Read more
*Apple* / Mac Administrator - JAMF - Amentum...
Amentum is seeking an ** Apple / Mac Administrator - JAMF** to provide support with the Apple Ecosystem to include hardware and software to join our team and Read more
Child Care Teacher - Glenda Drive/ *Apple* V...
Child Care Teacher - Glenda Drive/ Apple ValleyTeacher Share by Email Share on LinkedIn Share on Twitter Read more
Cashier - *Apple* Blossom Mall - JCPenney (...
Cashier - Apple Blossom Mall Location:Winchester, VA, United States (https://jobs.jcp.com/jobs/location/191170/winchester-va-united-states) - Apple Blossom Mall Read more
All contents are Copyright 1984-2011 by Xplain Corporation. All rights reserved. Theme designed by Icreon.