Click here to Skip to main content
15,881,757 members
Articles / Programming Languages / C++
Article

Two More Words

Rate me:
Please Sign up or sign in to vote.
4.53/5 (12 votes)
21 Jan 20077 min read 83.6K   699   36   10
Learn how to integrate MS Word functionality with your JScript/WSH scripting solutions.

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:

    JavaScript
    var WordApp = new ActiveXObject("Word.Application");

    Then, you create a document:

    JavaScript
    WordApp.Documents.Add();

    If you wish to show a Word window to a user, you add:

    JavaScript
    WordApp.Visible = true;
  • Starting a document from a template.

    When you have a document template, you may wish to use:

    JavaScript
    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:

      UnitValue
      Character1
      Word2
      Sentence3
      Paragraph4
      Line5
      Story6

      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.

    JavaScript
    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:

    JavaScript
    WordApp.Selection.TypeText("Text here");
  • Adding text to a field.

    Useful for field-based documents (reports, etc.):

    JavaScript
    // 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.
    JavaScript
    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:

      RuleValue
      Align left0
      Align center1
      Align right2
      Justify3
      Distribute4
    • 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-Dash7
      Underline-Dash-Heavy23
      Underline-Dash-Long39
      Underline-Dash-Long-Heavy55
      Underline-Dot-Dash9
      Underline-Dot-Dash-Heavy25
      Underline-Dot-Dot-Dash10
      Underline-Dot-Dot-Dash-Heavy26
      Underline-Dotted4
      Underline-Dotted-Heavy20
      Underline-Double3
      Underline-None0
      Underline-Single1
      Underline-Thick6
      Underline-Wavy11
      Underline-Wavy-Double43
      Underline-Wavy-Heavy27
      Underline-Words2

    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:

    JavaScript
    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:

    JavaScript
    // 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:
      JavaScript
      WordApp.Selection.Copy()
    • Cut - copies the contents of the Selection to the clipboard, and removes them from the document:
      JavaScript
      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.
      JavaScript
      WordApp.Selection.Paste()
  • Saving a document.

    You've done with changes?

    JavaScript
    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.
    JavaScript
    WordApp.Quit();

Formatting a letter.

First, the sample programmatically creates a business letter and saves it to the current directory.

JavaScript
// 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.

JavaScript
// 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
<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


Written By
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. Pin
Sandesh Omar7-Jul-08 23:20
Sandesh Omar7-Jul-08 23:20 
GeneralWant to copy of some of contents in Word Doc to Excel Sheet Pin
Sandesh Omar7-Jul-08 23:19
Sandesh Omar7-Jul-08 23:19 
QuestionHow retrieve status bar information. Such as current number line? Pin
Antonio292913-May-08 22:50
Antonio292913-May-08 22:50 
Generalgood start Pin
kimwong1-Sep-07 4:51
kimwong1-Sep-07 4:51 
GeneralRe: good start Pin
Dmitry Khudorozhkov1-Sep-07 5:29
Dmitry Khudorozhkov1-Sep-07 5:29 
GeneralRe: good start Pin
kimwong1-Sep-07 5:58
kimwong1-Sep-07 5:58 
GeneralRe: good start Pin
Dmitry Khudorozhkov1-Sep-07 6:04
Dmitry Khudorozhkov1-Sep-07 6:04 
GeneralError handling and additional navigation methods Pin
daluu31-Mar-06 10:03
daluu31-Mar-06 10:03 
Nice article, I just wanted to point out 2 things.

1. Error handling - it is sometimes a good idea to add this into the code as Word could behave erratic across different system setups or between different versions of Word. When Word throws an unanticipated error, you could be left with a Word object that hasn't been disposed, etc.

Using a try/catch block on a possibly finicky line of code is the best safety precaution:

<br />
try{<br />
//normal code here<br />
}catch(err){<br />
//error handling & cleanup routines here<br />
}<br />


2. Additional navigation methods - you can also use (1) the Find feature of Word within the Selection object to navigate the document, as well as (2) the hyperlink follow feature:

<br />
//WordObj.Selection.Find.Execute("text",case-sensitivity,...);<br />
WordObj.Selection.Find.Execute("text");<br />
	if(WordObj.Selection.Find.Found){<br />
    		//cursor now at start of found text, do something<br />
	}else{<br />
                //no change in cursor position<br />
		WScript.Echo("Failed to find the text in the document.");<br />
	}<br />
<br />
//or after finding a document hyperlink in word<br />
WordObj.Selection.Hyperlinks(1).Follow();<br />
//this will bring you to the beginning of the hyperlinked source<br />

GeneralExcellent! Pin
JohnDeHope35-Jan-06 16:23
JohnDeHope35-Jan-06 16:23 
GeneralRe: Excellent! Pin
daluu31-Mar-06 10:13
daluu31-Mar-06 10:13 

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

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