Click here to Skip to main content
Click here to Skip to main content

Two More Words

By , 21 Jan 2007
Rate this:
Please Sign up or sign in to vote.

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 Units. If Count is a positive number, the selection is collapsed to its end position and moved forward in the document by Count number of Units. If Count is a negative number, the selection is collapsed to its start position and moved backward by Count number of Units.

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

    • MoveEnd(Unit, Count)

      Moves the end position of the selection by Count number of Units.

    • 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);
    // Chars "tio" from "Selection" are now selected.
  • 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.):

    // For text field
    WordApp.ActiveDocument.FormFields("TextFieldName").Result = String;
    // For checkbox field
    WordApp.ActiveDocument.FormFields("CheckFieldName").CheckBox.Value = 
                                                         {true | false};
    // For drop-down-list field
    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:

    // Adding some text
    WordApp.Selection.TypeText("Some chars are different from others");
    
    // Moving the selection to 'different' word:
    WordApp.Selection.MoveStart(1, -21);
    WordApp.Selection.MoveEnd(1, -12);
    WordApp.Selection.Font.Superscript = 1;
    
    // Move selecton to the end of a phrase:
    WordApp.Selection.MoveEnd(1, 12);
    WordApp.Selection.Collapse(0);
    WordApp.Selection.Font.Superscript = 0;
    
    // Continue typing...
  • 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:

    • Copy - copies the contents of the Selection to the clipboard:
      WordApp.Selection.Copy()
    • Cut - copies the contents of the Selection to the clipboard, and removes them from the document:
      WordApp.Selection.Cut()
    • Paste - inserts the contents of the clipboard at the position specified by the Selection object. If Selection is not collapsed, it's contents are replaced by the contents of the clipboard.
      WordApp.Selection.Paste()
  • 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.

// Start a new instance of Microsoft Word
var WordApp = new ActiveXObject("Word.Application");

// Create a new document
WordApp.Documents.Add();
// Uncomment the following to see the Word window:
// WordApp.Visible = true;

WordApp.Selection.TypeParagraph();
WordApp.Selection.TypeParagraph();
WordApp.Selection.TypeParagraph();
WordApp.Selection.TypeParagraph();
WordApp.Selection.TypeParagraph();
WordApp.Selection.TypeParagraph();
WordApp.Selection.TypeParagraph();

// Add text header:
WordApp.Selection.ParagraphFormat.Alignment = 1;
//wdAlignParagraphRight = 2, wdAlignParagraphCenter = 1
WordApp.Selection.TypeText("Dear Customer,");

WordApp.Selection.TypeParagraph();
WordApp.Selection.TypeParagraph();

// Add main text:
WordApp.Selection.ParagraphFormat.Alignment = 3;
//wdAlignParagraphJustify = 3
WordApp.Selection.ParagraphFormat.FirstLineIndent = 10;
WordApp.Selection.TypeText("We are very sorry" + 
        " to hear that our Push-O-MaticTM");

// Show trademark sign as a superscript:
WordApp.Selection.MoveStart(1, -2);
WordApp.Selection.MoveEnd(1, 0);
WordApp.Selection.Font.Superscript = 1;

// Continue typing a text:
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.");

// Add a signature:
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.");

// Save & exit:
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.

// Start a new instance of Microsoft Word
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()" <BR>        value="Selection -&gt; MS Word"></INPUT>

 </BODY>
</HTML>

History

  • Posted: December 26, 2005.
  • Updated: January 20, 2007.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here

About the Author

Dmitry Khudorozhkov
Software Developer Freelance software engineer
Russian Federation Russian Federation
Dmitry Khudorozhkov began programming (and gaming) with his ZX Spectrum in 1989. Having seen and used all IBM PCs from early XT to the latest x64 machines, now Dmitry is a freelance programmer, living in Moscow, Russia. He is a graduate of the Moscow State Institute of Electronics and Mathematics (Applied Mathematics).
 
He is proficient in:
 
- C/C++ - more that 9 years of experience. Pure Win32 API/MFC desktop programming, networking (BSD/Win sockets), databases (primarily SQLite), OpenGL;
 
- JavaScript - more that 6 years of experience. Client-side components, AJAX, jQuery installation and customization;
 
- Firefox extensions (immediatelly ready for addons.mozilla.org reviewing) and Greasemonkey scripts. As an example of extensions Dmitry made you can search for FoxyPrices or WhatBird Winged Toolbar;
 
- XML and it's applications (last 2 years): XSLT (+ XPath), XSD, SVG, VML;
 
- ASP.NET/C# (webservices mostly);
 
Also familiar with (= entry level):
 
- PHP;
 
- HTML/CSS slicing.
 
Trying to learn:
 
- Ruby/Ruby-on-Rails;
 
- Czech language.
 
If you wish to express your opinion, ask a question or report a bug, feel free to e-mail:dmitrykhudorozhkov@yahoo.com. Job offers are warmly welcome.
 
If you wish to donate - and, by doing so, support further development - you can send Dmitry a bonus through the Rentacoder.com service (registration is free, Paypal is supported). Russian users can donate to the Yandex.Money account 41001132298694.
 
-

Comments and Discussions

 
QuestionI need to copy selected contents in word doc to excel sheet. PinmemberSandesh Omar7-Jul-08 23:20 
GeneralWant to copy of some of contents in Word Doc to Excel Sheet PinmemberSandesh Omar7-Jul-08 23:19 
QuestionHow retrieve status bar information. Such as current number line? PinmemberAntonio292913-May-08 22:50 
Generalgood start Pinmemberkimwong1-Sep-07 4:51 
GeneralRe: good start PinmemberDmitry Khudorozhkov1-Sep-07 5:29 
GeneralRe: good start Pinmemberkimwong1-Sep-07 5:58 
GeneralRe: good start PinmemberDmitry Khudorozhkov1-Sep-07 6:04 
GeneralError handling and additional navigation methods Pinmemberdaluu31-Mar-06 10:03 
GeneralExcellent! PinmemberJohnDeHope35-Jan-06 16:23 
GeneralRe: Excellent! Pinmemberdaluu31-Mar-06 10:13 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Mobile
Web03 | 2.8.140421.2 | Last Updated 22 Jan 2007
Article Copyright 2006 by Dmitry Khudorozhkov
Everything else Copyright © CodeProject, 1999-2014
Terms of Use
Layout: fixed | fluid