Team LiB
Previous Section Next Section

4.7. Commanding Microsoft Word

If TextEdit were a sardine, Microsoft Word would be a blue whale. Mentioning the two together invites all sorts of comparisons: TextEdit takes up 5 MB, while Word takes up 20; TextEdit has six menus, Word has a dozen. The two programs, in fact, are illustrative of their respective companies' approaches: TextEdit is straightforward and simple, while Word is complex and feature-packed.

Still, Word's AppleScript support puts TextEdit to shame. Word includes the standard Text Suite (Section 4.6.1) but adds more than 50 commands of its own.

Many of Word's cool AppleScript commands are available only in the most recent release: Word 2004. Therefore, to ensure that the scripts in this chapterand the rest of this bookwork properly for you, you'd be best off upgrading to Word 2004 for the sake of compatibility.

4.7.1. Adapting a TextEdit Script

In Section 4.6.1, you created a script that counted the number of characters, words, and paragraphs in an open TextEdit document. Of course, Word already has a word count feature (Tools Word Count). Still, it's a good exercise to adapt your existing TextEdit script for use with Word, to get a feel for the differences in what it's like to script the two programs.

The first step in adapting a TextEdit script is to replace the tell statement with one that directs Word instead of TextEdit.

tell application "Microsoft Word"
    activate
    . . .
end tell

You must use the phrase "Microsoft Word" in AppleScript; "Word" won't suffice.

Up to Speed
The count Command

In the previous script, you used the count command for the first time, to figure out how many words are in a TextEdit document. You'll encounter count again in all sorts of scripts, though, so it's important to understand how it works.

In essence, count takes a list and returns how many items are inside it. You can take advantage of this command for all sorts of tasks, from counting seashells in a beach-simulation script to counting employees in an employee-management script.

Like the exists command, count can come either before or after the object you want to count. That means that both of the following are acceptable commands in AppleScript:

count allCharacters --Works
allCharacters count --Also works

You'll often see the count command used in conjunction with the every keyword (Section 6.3), too. This powerful duo lets you get all the objects of a certain type (like all the words in a TextEdit document) and then count them. You can even use this command pair to get the number of items in a folder, like this:

tell application "Finder"
    set itemNumber to (count every item ¬
    in the folder "Applications")
    display dialog "You have " & ¬
    itemNumber & " items inside your ¬
    Applications folder."
end tell

Finally, in a quite specialized use, you can use the count command on its own to figure out how many characters are in a string. This would be helpful if you ever needed to confirm that an essay hadn't exceeded your professor's 10,000 character limit, for example. Or, you could find out how many characters are in your first name with this script:

set yourName to the text returned of ¬
(display dialog ¬
    "Enter your first name:" default ¬
    answer "Xavier")
set numChars to (count yourName)
display dialog "Your name has " &  ¬
    numChars & " characters."


If you run the script at this point, you'll get a strange result: both the character and word counts will be 0. This is caused by an odd quirk in Microsoft Word, which requires that you use the count and every keywords on the same line. To get your script to work properly, therefore, you must merge some of your existing lines to create this new script:

tell application "Microsoft Word"
    activate
    --Count the characters:
    set numberOfCharacters to (count every character of the front document)
    set characterText to "Characters: " & numberOfCharacters
    --Count the words:
    set numberOfWords to (count every word of the front document)
    set wordText to "Words: " & numberOfWords
    --Count the paragraphs:
    set numberOfParagraphs to (count every paragraph of the front document)
    set paragraphText to "Paragraphs: " & numberOfParagraphs
    --Assemble the text for the dialog box:
    set dialogText to characterText & return & wordText & return ¬
        & paragraphText
    display dialog dialogText
end tell

Workaround Workshop
Word Miscounting

When you run the script on this page, you see a dialog box listing the character, word, and paragraph counts from your frontmost Microsoft Word document. Unfortunately, this word count often conflicts with the results of Word's included word count feature (Tools Word Count).

This problem occurs because AppleScript, when commanding Microsoft Word, considers punctuation marks their own words. That means Microsoft Word would see three words in "Don't eat yams!", but AppleScript would see five (the three words, plus two punctuation marks). Of course, this can distort your word counts considerablyespecially if you're the type that likes to insert dashes in the middle of your sentences.

Fortunately, you can dodge AppleScript's fuzzy math by communicating with a Microsoft Word text objectan abstract AppleScript item that represents the text inside a particular document. Unlike communicating with a document directly, communicating with a text object actually produces an accurate word count. So, to remedy your script, you could simply make the following changes:

tell application "Microsoft Word"
    set theText to the content of the ¬        text object of the front document
    set numberOfCharacters to ¬
        (count every character of theText)
    set characterText to "Characters: " ¬
        & numberOfCharacters
    set numberOfWords to  ¬
        (count every word of theText)
    set wordText to "Words: " & ¬
        numberOfWords
    set numberOfParagraphs to (count ¬
        every paragraph of theText)
    set paragraphText to "Paragraphs: " ¬
        & numberOfParagraphs
    set dialogText to characterText & ¬
        return & wordText & ¬
        return & paragraphText
    display dialog dialogText
end tell

Now when you run your modified script, your word count reflects the actual number of words in your documentwithout counting punctuation.


You'll notice that the two-liners that counted various itemsfor example, set allWords to every word of the front document and set numberOfWords to (count allWords)have been put together into single-line commands. This is enough to satisfy Word's requirement for using count and every together; when you run the script now, it works properly.

When writing your own scripts for different programs, make sure to try using count and every together (as used here) and on different lines. Chances are, the script will work at least one of the ways, but the only way to find out is to try both.

4.7.2. Shrinking Documents by a Page

If you write letters or emailsor computer books, for that matteryou've probably experienced the dreaded one-page-too-long problem. It goes like this: you're typing your document, inserting all sorts of different fonts and sizes, but when you come to the end, you realize your document is just one page longer than you want it.

If you're like most people, you'd sigh deeply, and then get to work modifying each individual font in your document, shrinking them in size so the document is one page shorter. The trouble with this approach, of course, is that it can take a long time to select blocks of text and change their font sizes, especially if you need to modify multiple fonts on dozens of pages.

Word, conveniently enough, provides an AppleScript command to take care of this whole text-squeezing business for you: fit to pages. The trouble is, though, that Word has hundreds of different commands in its dictionary. Does Microsoft really expect you to spend several minutes scanning all the entries in the left pane to find the fit to pages command? Yep.

Still, you purchased this book to save you some time, and you can prove Microsoft wrong. Once you've opened Word's dictionary (Section 3.2.2), simply follow the procedure in Figure 4-7 to find the correct dictionary entry.

The definition of the command (also shown in Figure 4-7) tells you that it's meant to squeeze your fonts "just enough so that the document will fit on one fewer pages." The light blue document text, furthermore, indicates that you have to tell fit to pages which document you want it to work with.

Armed with this information, you can write your script:

tell application "Microsoft Word"
    activate
    display dialog "Shrink document by a page?"
    fit to pages (front document)
end tell

When you run this script, make sure you have an open Word file that's more than one page long, so the fit to page command has something to perform its magic on.

This script brings Microsoft Word forward and then displays a confirmation dialog box, asking you if you want to shrink the document by a page. Since you haven't defined special buttons for the dialog box (Sidebar 4.2), you're left with only two options:

  • If you click OK, the script proceeds with the next statement (fit to pages) and squeezes the front document down by one page.

  • If you click Cancel, the script ends immediately.

After clicking OK, Word checks what it'll take to knock one page off your document and adjusts the font sizes throughout the document until the mission is complete.

Figure 4-7. Once you've opened the dictionary, click once inside the left pane. Top: Then choose Edit Find Find, and enter the command you want to find.Bottom left: The first time you click Next, the dictionary reveals which suite contains your command (in this example, the Microsoft Word Suite). You've just narrowed down your choices considerably.Bottom right: When you click Next a second time, the dictionary jumps straight to the entry for the command you searched for.


4.7.3. Repeating the Shrinking

The script you have so far is convenient, but what if you wanted to shrink your document by more than just one page? For example, you might be badgered for writing too much in a business proposal but find it easier to shrink the size of your writing than to actually cut text out.

In this situation, of course, you could run your script more than once, returning to Script Editor each time to click Run again. But that would defeat the purpose of using AppleScript in the first place: to automate tasks that you would normally have to do by hand.

Instead, you might as well have AppleScript repeat the fit to pages command all by itself, so you can go ride your bike while AppleScript chugs along on its font-shrinking mission.

The key to repeating a command in AppleScript is to use a repeat statement. Such statements generally follow this format:

repeat <some number> times
    --Commands you want to repeat go here
end repeat

When AppleScript encounters a repeat statement, it goes through the commands insideone at a timeand then repeats the entire process however many times you specify. For running the fit to page command multiple times, you simply have to add a repeat statement to your existing script, as shown here:

tell application "Microsoft Word"
    activate
    display dialog "Shrink document by 5 pages?"
    repeat 5 times
        fit to pages (front document)
    end repeat
end tell

Now when you run the script, Word tries to shrink the front document by five pages instead of just one. (It accomplishes this, of course, by repeating the fit to page command five times.)

4.7.4. Shrinking a Variable Number of Times

Again, the script you have is convenient. However, it still lacks one crucial feature: you can't specify how many times you want it to repeat (at least, not without changing the numbers in Script Editor by hand). It would be great if, using a dialog box, you could have the script ask how many times to repeat the fit to pages command.

To do so, you simply have to change a few more lines of your script:

tell application "Microsoft Word"
    activate
    set theNumber to the text returned of (display dialog ¬
        "Shrink by how many pages?" default answer 3)
    repeat theNumber times
        fit to pages (front document)
    end repeat
end tell

Now the repeat statement runs however many times you specify in the dialog box. In other words, you get to tell Word how many pages you want to shrink the front document by, instead of hard-coding that number into the script. That's the power of AppleScript for you!

There are other instances when you might want to use repeat statements, including:

  • Renaming multiple files automatically (Section 6.4.1)

  • Repeating a computerized beep at regular intervals to create a virtual metronome (Sidebar 8.1)

  • Rating every song in your iTunes library (Section 8.1.2)

    Team LiB
    Previous Section Next Section