AppleScript Programming/Sample Programs/MS Word 2008

From Wikibooks, open books for an open world
Jump to: navigation, search

Microsoft Word 2008 and its Office brethren are a completely different animal when it comes to scripting. The majority of the code needed to script Word comes from the same object hierarchy as the (at the time of this writing) dead Visual Basic for Mac.

The script below creates a new Word document, and inserts predefined text. Then the text is formatted.


--This is just where we define our variable fiHR and could be returned from any interview or picked up and parsed through an external program. We have cheated a bit by using AppleScripts built in language to pre-format our text, however AppleScript, itself, knows nothing about text styling (bold, fonts etc.) applications like Text Edit and MS Word do though.

set fiHR to "Facts" & return & return & return & return & "Issue" & return & return & return & return & "Holding" & return & return & return & return & "Rationale"

--telling Microsoft Word to startup and come to front

tell application "Microsoft Word" activate

--telling MS Word to create a new document, as opposed to "active document"

create new document

--this defines the area for all of the text of the new document, start 0 end 0 captures the whole doc, with existing docs you could call out words, characters, lines in paragraphs etc.

set myRange to create range active document start 0 end 0

--now we are setting what the contents of text, for the whole document (myRange), should be, by calling our variable (fiHR) which we have previously defined

set content of myRange to fiHR

--this line sets our cursor/insertion point to the end of our text. it could be set to a character, word, line paragraph etc. Story is everything we have typed into the new doc. We do this, because we want the formatting to apply to all of the text typed in from our variable.

set myRange to change end of range myRange by a story item ¬ extend type by selecting

--begin formatting the text fiHR by setting the font and the styling of the font

set name of font object of myRange to "Arial"

set italic of font object of myRange to true

--telling Microsoft Word that we are done bossing it around for now. We have not saved nor closed this doc, but that could be added too.

end tell

code by SolutionArts.net