Introduction
Automation tech is very useful when you need to programmatically create, edit, or somehow control various documents. The main problem is that most of Office-scripting-related documentation is written in Visual Basic or WordBasic. For those unfamiliar with the subject, this article can be treated as a quick introduction to MS Word automation; for others, this article is a short transitional reference.
This article assumes you are familiar with JScript.
General HOWTO's
- Starting a blank document.
First, you create an application:
var WordApp = new ActiveXObject("Word.Application");
Then, you create a document:
WordApp.Documents.Add();
If you wish to show a Word window to a user, you add:
WordApp.Visible = true;
- Starting a document from a template.
When you have a document template, you may wish to use:
WordApp.Documents.Add("TemplateName.dot");
instead of simply starting a blank document.
- Working with selection and navigating through the document.
Figure 1. Collapsed selection (left, I-beam cursor) and ranged selection (right).
Moving Selection
is the main navigational technique. It is useful to think of Selection
like the I-beam cursor that you see every time you open your favourite text processor. The available methods are:
Collapse(Direction)
Collapses a selection selection to the starting or ending position. After a selection is collapsed, the starting and ending points are equal. Direction
can be either wdCollapseStart
(value: 1), or wdCollapseEnd
(value: 0).
Move(Unit, Count)
Collapses the selection to its start position or end position and then moves the collapsed object by Count
number of Unit
s. If Count
is a positive number, the selection is collapsed to its end position and moved forward in the document by Count
number of Unit
s. If Count
is a negative number, the selection is collapsed to its start position and moved backward by Count
number of Unit
s.
A Unit
can be one of the following:
Unit |
Value |
Character |
1 |
Word |
2 |
Sentence |
3 |
Paragraph |
4 |
Line |
5 |
Story |
6 |
Through Collapse
and Move
methods, you work with Selection
like with an I-beam cursor; the following methods allow you to select not the position, but a range of characters, words, etc:
MoveStart(Unit, Count)
Moves the start position of the selection by Count
number of Unit
s.
MoveEnd(Unit, Count)
Moves the end position of the selection by Count
number of Unit
s.
MoveStartWhile(CharSet, Count)
/MoveEndWhile(CharSet, Count)
Moves the start/end position of the selection while any of the characters, listed in CharSet
, are found in the document. Count
is an optional parameter, specifying the maximum number of characters by which the selection is to be moved. Can be a number, or either the wdForward
(value: 1073741823) or wdBackward
(value: -1073741823) constant. If Count
is a positive number, the selection is moved forward in the document. If it's a negative number, the selection is moved backward.
MoveStartUntil(CharSet, Count)/MoveEndUntil(CharSet, Count)
Moves the start/end position of the selection until any of the characters, listed in CharSet
, are found in the document. Count
is an optional parameter, specifying the maximum number of characters by which the selection is to be moved. Can be a number, or either the wdForward
(value: 1073741823) or wdBackward
(value: -1073741823) constant. If Count
is a positive number, the selection is moved forward in the document. If it's a negative number, the selection is moved backward.
WordApp.Selection.TypeText("Selection")
WordApp.Selection.MoveStart(1, -4);
WordApp.Selection.MoveEnd(1, -1);
- Adding text.
The most frequently used command is:
WordApp.Selection.TypeText("Text here");
- Adding text to a field.
Useful for field-based documents (reports, etc.):
WordApp.ActiveDocument.FormFields("TextFieldName").Result = String;
WordApp.ActiveDocument.FormFields("CheckFieldName").CheckBox.Value =
{true | false};
WordApp.ActiveDocument.FormFields("DropDownFieldName").DropDown.Value =
number-index;
- Typing a new line.
WordApp.Selection.TypeParagraph();
- Formatting a paragraph.
If you wish to apply styles to your text, you have two objects at your disposal: WordApp.Selection.ParagraphFormat
and WordApp.Selection.Font
.
The most commonly used properties of the ParagraphFormat
object are:
Alignment
= {alignment-value}
Sets the alignment rule according to the value:
Rule |
Value |
Align left |
0 |
Align center |
1 |
Align right |
2 |
Justify |
3 |
Distribute |
4 |
FirstLineIndent
= {number}
Sets the value (in points) for the first line or a hanging indent. Use a positive value to set a first-line indent, and use a negative value to set a hanging indent.
KeepTogether
= {true
(non-zero)/false
(zero)}
Set a non-zero value if all the lines in a paragraph remain on the same page when Word repaginates the document; set zero if they do not.
KeepWithNext
= {true
(non-zero)/false
(zero)}
Set non-zero value if the current paragraph remains on the same page as the paragraph that follows it when Word repaginates the document; set zero if it does not.
LeftIndent
= {number}, RightIndent
= {number}
Sets the left/right indent value (in points) for the paragraph.
LineSpacing
= {number}
Sets the line spacing (in points) for the paragraph.
SpaceAfter
= {number}, SpaceBefore
= {number}
Sets the spacing (in points) after/before the paragraph.
The most commonly used properties of the Font
object are:
AllCaps
= {true
(non-zero)/false
(zero)}
Set a non-zero value if the font should be formatted as all capital letters; set zero if it shouldn't.
Bold
= {true
(non-zero)/false
(zero)}
Set non-zero value if the font should be formatted as bold text; set zero if it shouldn't.
DoubleStrikeThrough
= {true
(non-zero)/false
(zero)}
Set non-zero value if the font should be formatted as double strikethrough text; set zero if it shouldn't.
Emboss
= {true
(non-zero)/false
(zero)}, Engrave
= {true
(non-zero)/false
(zero)}
Set non-zero value if the font should be formatted as embossed/engraved; set zero if it shouldn't.
Italic
= {true
(non-zero)/false
(zero)}
Set non-zero value if the font should be formatted as italic; set zero if it shouldn't.
Position
= {number}
Sets the position of text (in points) relative to the base line. A positive number raises the text, and a negative number lowers it.
Name
= {string}
Sets the name of the font.
Shadow
= {true
(non-zero)/false
(zero)}
Set a non-zero value if the font should be formatted as shadowed; set zero if it shouldn't.
Size
= {number}
Sets the font size, in points.
SmallCaps
= {true
(non-zero)/false
(zero)}
Set non-zero value if the font should be formatted as small capital letters; set zero if it shouldn't.
Spacing
= {number}
Sets the spacing between characters, in points.
StrikeThrough
= {true
(non-zero)/false
(zero)}
Set non-zero value if the font should be formatted as strikethrough text; set zero if it shouldn't.
Subscript
= {true
(non-zero)/false
(zero)}
Set non-zero value if the font should be formatted as subscript; set zero if it shouldn't.
Superscript
= {true
(non-zero)/false
(zero)}
Set non-zero value if the font should be formatted as superscript; set zero if it shouldn't.
Underline
= {underline-type-value}
Sets the type of underline applied to the font. Available types are:
Type
| Value |
Underline-Dash |
7 |
Underline-Dash-Heavy |
23 |
Underline-Dash-Long |
39 |
Underline-Dash-Long-Heavy |
55 |
Underline-Dot-Dash |
9 |
Underline-Dot-Dash-Heavy |
25 |
Underline-Dot-Dot-Dash |
10 |
Underline-Dot-Dot-Dash-Heavy |
26 |
Underline-Dotted |
4 |
Underline-Dotted-Heavy |
20 |
Underline-Double |
3 |
Underline-None |
0 |
Underline-Single |
1 |
Underline-Thick |
6 |
Underline-Wavy |
11 |
Underline-Wavy-Double |
43 |
Underline-Wavy-Heavy |
27 |
Underline-Words |
2 |
There is only one rule you must be aware of when changing paragraph/font styles: property, once changed, preserves its state till the next change, or, if no changes are introduced, for the rest of the document. For fonts, this rule works only is your Selection
is collapsed; if it is not, then the font change applies only to the range selected. In other words, you should keep track of all changes to font/paragraph styles.
For example:
WordApp.Selection.TypeText("Ordinary text here");
...
WordApp.Selection.Font.Superscript = 1;
WordApp.Selection.TypeText("Superscripted text here and further on");
...
WordApp.Selection.Font.Superscript = 0;
WordApp.Selection.TypeText("Normal text again");
- Formatting distinct characters.
Navigational mumbo-jumbo combined with the powers of Font
gives us a method to control the styles of individual characters:
- move a selection's start/end to the appropriate position, so that the selection wraps the required paragraphs/words/characters;
- change the properties of
Selecton.Font
;
- collapse the selection;
- restore font properties (so you continue typing with normal font).
Example:
WordApp.Selection.TypeText("Some chars are different from others");
WordApp.Selection.MoveStart(1, -21);
WordApp.Selection.MoveEnd(1, -12);
WordApp.Selection.Font.Superscript = 1;
WordApp.Selection.MoveEnd(1, 12);
WordApp.Selection.Collapse(0);
WordApp.Selection.Font.Superscript = 0;
- Working with the clipboard.
Clipboard is your main communication channel between automated applications. It also makes transfers of large chunks of text easier.
Selection
object. Basic methods are:
- Saving a document.
You've done with changes?
var Path = WScript.ScriptFullName;
Path = Path.substring(0, Path.lastIndexOf("\\"));
WordApp.ActiveDocument.SaveAs(Path + "/letter.doc");
Magic with WScript.ScriptFullName
is needed if you wish to save a document to folder where your script is; without it, Word will save your document to the default folder (usually to the My Documents folder).
- Exiting.
WordApp.Quit();
Formatting a letter.
First, the sample programmatically creates a business letter and saves it to the current directory.
var WordApp = new ActiveXObject("Word.Application");
WordApp.Documents.Add();
WordApp.Selection.TypeParagraph();
WordApp.Selection.TypeParagraph();
WordApp.Selection.TypeParagraph();
WordApp.Selection.TypeParagraph();
WordApp.Selection.TypeParagraph();
WordApp.Selection.TypeParagraph();
WordApp.Selection.TypeParagraph();
WordApp.Selection.ParagraphFormat.Alignment = 1;
WordApp.Selection.TypeText("Dear Customer,");
WordApp.Selection.TypeParagraph();
WordApp.Selection.TypeParagraph();
WordApp.Selection.ParagraphFormat.Alignment = 3;
WordApp.Selection.ParagraphFormat.FirstLineIndent = 10;
WordApp.Selection.TypeText("We are very sorry" +
" to hear that our Push-O-MaticTM");
WordApp.Selection.MoveStart(1, -2);
WordApp.Selection.MoveEnd(1, 0);
WordApp.Selection.Font.Superscript = 1;
WordApp.Selection.Collapse(0);
WordApp.Selection.Font.Superscript = 0;
WordApp.Selection.TypeText(" toy doesn�t push properly." +
" It was working perfectly by the time we sent it to you. ");
WordApp.Selection.TypeText("Please be assured that" +
" we shall scrupulously investigate the cause.");
WordApp.Selection.TypeParagraph();
WordApp.Selection.TypeParagraph();
WordApp.Selection.TypeText("Your purchase will be replaced" +
" in a week; we thank you for patience.");
WordApp.Selection.TypeParagraph();
WordApp.Selection.TypeParagraph();
WordApp.Selection.TypeParagraph();
WordApp.Selection.TypeParagraph();
WordApp.Selection.TypeParagraph();
WordApp.Selection.TypeParagraph();
WordApp.Selection.TypeParagraph();
WordApp.Selection.TypeParagraph();
WordApp.Selection.TypeParagraph();
WordApp.Selection.TypeParagraph();
WordApp.Selection.TypeParagraph();
WordApp.Selection.TypeParagraph();
WordApp.Selection.TypeParagraph();
WordApp.Selection.TypeParagraph();
WordApp.Selection.TypeParagraph();
WordApp.Selection.TypeParagraph();
WordApp.Selection.TypeParagraph();
WordApp.Selection.TypeParagraph();
WordApp.Selection.TypeParagraph();
WordApp.Selection.TypeParagraph();
WordApp.Selection.ParagraphFormat.Alignment = 2;
WordApp.Selection.TypeText("Sincerely yours,");
WordApp.Selection.TypeParagraph();
WordApp.Selection.TypeText("William Gates IX Jr.,");
WordApp.Selection.TypeParagraph();
WordApp.Selection.TypeText("PleasureToys Inc, CEO.");
var Path = WScript.ScriptFullName;
Path = Path.substring(0, Path.lastIndexOf("\\"));
WordApp.ActiveDocument.SaveAs(Path + "/letter.doc");
WordApp.Quit();
Formatting a report
This sample utilizes the document template (ReturnAndUplift.dot, see the accompanying zip archive) along with an extensive use of fields.
var WordApp = new ActiveXObject("Word.Application");
var Path = WScript.ScriptFullName;
Path = Path.substring(0, Path.lastIndexOf("\\"));
// Create a new document
WordApp.Documents.Add(Path + "/ReturnAndUplift.dot");
// Comment the following to hide the Word window:
WordApp.Visible = true;
var dt = new Date();
WordApp.ActiveDocument.FormFields("DateOfReport").Result =
(dt.getMonth() + 1) + "/" + dt.getDate() + "/" + dt.getFullYear();
WordApp.ActiveDocument.FormFields("OrderID").Result = "8765-4321";
WordApp.ActiveDocument.FormFields("ProducedBy").Result = "J. C. Denton";
WordApp.ActiveDocument.FormFields("StoreName").Result = "Store-456";
WordApp.ActiveDocument.FormFields("CustomersName").Result = "John C.";
WordApp.ActiveDocument.FormFields("Address").Result = "14 Street, 21";
WordApp.ActiveDocument.FormFields("CityTown").Result = "NY";
WordApp.ActiveDocument.FormFields("PostCode").Result = "1234-5678";
// Uncomment the followng lines to automatically save & exit:
// WordApp.ActiveDocument.SaveAs(Path + "/letter.doc");
// WordApp.Quit();
Transferring text from MS IE to Word
This sample shows how to use the clipboard to transfer text from a web page to Word document. Unlike two previous sample, this one is not the stand-alone script; it is a web page, and script inside it utilizes both MS IE user javascript and Word scripting capabilities. It should be opened with Internet Explorer.
<HTML>
<HEAD>
<SCRIPT type="text/javascript">
function SelectionToWord()
{
// Determine a selection:
var select = document.selection;
var range = select.createRange();
// If selection is not empty:
if(range.text.length)
{
// Copy selection to clipboard:
range.execCommand("Copy");
// Start MS Word instance:
var word = new ActiveXObject("Word.Application");
// Create new document:
word.Documents.Add();
// Paste clipboard contents into the document:
word.Selection.Paste();
// Show MS Word:
word.Visible = true;
}
}
</SCRIPT>
</HEAD>
<BODY>
<P>Select a text and push a button.</P>
<P>blah-blah-blah <B>blah-blah-blah blah-blah-blah</B> blah-blah-blah<BR>
blah-blah-blah <B>blah-blah-blah blah-blah-blah</B> blah-blah-blah<BR>
blah-blah-blah <B>blah-blah-blah blah-blah-blah</B> blah-blah-blah<BR>
blah-blah-blah <B>blah-blah-blah blah-blah-blah</B> blah-blah-blah</P>
<INPUT type="button" onclick="SelectionToWord()"
value="Selection -> MS Word"></INPUT>
</BODY>
</HTML>
History
- Posted: December 26, 2005.
- Updated: January 20, 2007.