Microsoft Word Automation Class


Desktop-as-a-Service Designed for Any Cloud ? Nutanix Frame


Often, the main challenge in developing C++ automation solutions for Microsoft Office is the lack of detailed technical documentation for Office's OLE interface. At the same time, ample automation information for Visual Basic applications can be acquired by using Office macros and the Office Help Wizard. It would be natural to come with a tool that can be used to "translate" or "convert" Office's macros into code executable from C++. This approach was previously implemented in an MSVC Excel automation project and is described in the recent article on CodeGuru (see "Microsoft Excel Automation Class" by V. Golovlev).

In this article, the approach is modified for executing Microsoft Word functions from an MSVC application. The CWordAutomation class that implements this approach includes a small collection of OLE functions and also contains examples of code for some MS Office operations. Also, a CEzWordAutomation wrapper class is provided; it exposes a set of methods from CWordAutomation to perform basic access to MS Word documents.

The MSWordDemo project provides an example of using CWordAutomation and CEzWordAutomation to read and write text from and to MS Word documents, open and save Word files, and use the Word spell function to check word spelling in an MSVC application.

The CWordAutomation has two groups of methods: 1) to access OLE interface, and 2) to implement selected macros. The most essential methods from the first group include WordDispatch(...), AddArgumentCString(...), AddArgumentInt2(...), and ClearAllArgs(). The second group includes an example of implementating Word macros to create a new Word document, adding and reading text from the Word document, and opening/saving Word files:

  • CreateBlankDocument()
  • AppendText(CString szText)
  • GetLine(int nLine)
  • OpenWordFile(CString szFileName)
  • SaveWordFileAs(CString szFileName)
  • and some others.

The MSWordDemo project gives an example of using CWordAutomation and CEzWordAutomation. In this project, a Word document is viewed as a collection of lines (strings) that can be read from or written to the document. Each Word line can be accessed in the document by its line number (see CWordAutomation::GetLine(int nLine)). The total number of lines in the document is retrieved by GetLinesCount(). The user can add a new string (line) to the document by using the AppendText(...) method. The new text is appended at the end of the document. To move a large amount of data and copy text between Word documents, the CopyLinesToClipboard(...) method is available. Text is copied to a clipboard and subsequently can be pasted into the document by using the PasteText(...) method.

A Word application can be started in one of two modes: with the user interface exposed (bVisible = TRUE) or hidden (bVisible = FALSE). In the first mode, the document and Word interface are visible and available to the user. In the second mode (bVisible = FALSE), Word runs in the background with no interface exposed, but Word functions can be executed by MSVC code.

Adding a Word Automation Function to a MSVC Project

Add CWordAutomation and CEzWordAutomation classes to your project (see also "Microsoft Excel Automation Class" on how to add automation classes to the project). To start a new Word document, use this code in your application:

CEzWordAutomation MsWord;

To start Word in the background with no interface exposed to the user:

CEzWordAutomation MsWord(FALSE);

To release the document and close the Word application, call:


To open a Word file and get/create szFileName, call:


Also, see the WordDemo project for examples of implementating the CWordAutomation and CEzWordAutomation classes.

The WordDemo project provides examples of using the CWordAutomation and CEzWordAutomation classes to start a new Word document and add new text to the document by entering a single line (AppendText(...)) or by copying multiple lines by the copy/paste clipboard function. Other examples include methods to open and save Word files. Also included in this project is an example of using Word's spell engine to check word spelling from a C++ application.

To run the WordDemo application, Microsoft Word must be installed on your computer!

To run the demo program, compile and run the project.The WordDemo interface has two sections: one to demonstrate Word functions and the other to demonstrate spell checking using the Word speller:

Functions of the DemoProject Buttons

  • "Open New Word Doc": Opens a new Word document and enters text using the AppendText(...) method. The Word interface is visible.
  • "Paste to Word Doc": Opens a new Word document and enters text using clipboard functions CopyTextToClipboard(...) and PasteText(...). The Word interface is visible.
  • "Save Word File": start Word in background (i.e., interface is not visible), enter text to the document, open file dialog and save Word file.
  • "Open Word File": Starts a Word application, opens file dialog and the Word file. The Word interface is visible.
  • "Get Text": Starts a Word application in the background, opens the file dialog, reads the number of lines in the Word file selected by user, reads the first and last lines in the file, releases the Word application, and reports the number of lines in the file and contents of the first and last line to the user.
  • "Exit": Releases WordDemo.
  • "Spell check": Uses Word's spell engine to check spelling of the word the user entered. Word is started in the background mode after the user enters the word and clicks the "Check spelling" button. If Word's speller reports one or more alternative spellings, the very first entry from the collection of the alternative spellings replaces the word in the Edit box. After completion, the Word application is released.

Writing Code to Add a New Word Function

The first step is to write a macro that performs the user's function. For instance, the following macro returns the first entry from a collection of alternative spellings for the user's word szUserWord:

szNewSpelling = Application.GetSpellingSuggestions(Word:=
Note: To use this in MSVC method, the parameters MUST be named whenever possible. In a VB project, this macro works just fine:

But, to use it in MSVC, it has to be used with all parameters spelled out:


The next step is to add a new method to the CWordAutomation class and write the code. Each macro object, for instance MyMacroObject, is called in MSVC by a block of code as shown in the following code snippet:

if (!WordInvoke(vargParentObject.pdispVal,
   L" MyMacroObject ", &vargMyChildObject, DISPATCH_METHOD, 0))
   return FALSE;}

Observe the use of vargParentObject B and vargMyChildObject here. In this example, MyMacroObject is the child of the ParentObject, and it has also its own child object MyChildObject: ParentObject.MyMacroObject.MyChildObject

If MyMacroObject requires a parameter to be used: MyParameter:=wdParamValue, the MSVC code has to be modified to this:

AddArgumentInt2(L" MyParameter ", 0, wdParamValue);
if (!WordInvoke(vargParentObject.pdispVal, L" MyMacroObject ",
   &vargMyChildObject, DISPATCH_METHOD, 0))B return FALSE;}

In the above speller's example, the macro uses four objects. The corresponding code will consist of three blocks of {ClearAllArgs... WordInvoke}(in other words, N-1 of the number of objects used, see CWordAutomation::SpellWord(CString szWord) for details). If the macro returns a value, that value can be retrieved from the VARIANTARG returned by the last WordInvoke(...) call. To see a detailed example of retrieving value from a macro, please refer to the CWordAutomation::GetLine(int nLine) method in the MSWordDemo project.

Additional examples of MSVC codes for Office macros can be found in discussions posted on CodeGuru for "Microsoft Excel Automation Class."

The last step is to add the corresponding new method to EzWordAutomation. In most cases. it consists of a single line of code (see EzWordAutomation methods).

Thank you! Your comments are highly valuable!

About the Author

Val Golovlev

Physicist, now is working in life science research. Fan of C++ for six years; have used C++ in various projects for interfacing instruments, data processing; image acquisition and analysis, internet applications, databases, etc.



  • comment

    Posted by trägerloser bh on 10/28/2015 10:31pm

    Couldn't be written any better. Reading this post reminds me of my old room mate! He always kept talking about this. I will forward this article to him. Pretty sure he will have a good read. Thanks for sharing!

  • Fix for random crashes

    Posted by Marc-Antoine M. on 08/21/2015 11:06pm

    First I want to thank you for this COM wrapper, this is awesome! :-) To avoid random crashes with the function "ClearAllArgs()", you can initialize all the member variables of the CWordAutomation object in the constructors: CWordAutomation::CWordAutomation() { m_iArgCount = 0; m_iNamedArgCount = 0; m_pdispWordApp = NULL; int nIdx; for( nIdx=0; nIdx

  • Add and populate Table

    Posted by MAGLI LUIGI on 07/02/2015 11:23am

    Nice demo. How i can add and populate a table ? Thanks.

  • How do export pdf file in word doc?

    Posted by amber on 09/15/2014 01:29pm

    how do export the pdf file in word doc

  • How do I insert a merge field object

    Posted by Charles Aghedo on 09/19/2012 08:23pm

    Using your Microsoft Word Automation Class, id there a way I can insert a mail merge field into the Word document?

  • Thanks a lot

    Posted by vaibhavbvp on 09/04/2012 11:17am

    thanks for such a nice piece of work... i have a small query how to find the page number of a image??e.g suppose i have a document of 10 pages,which contains image on page 3,5,8.. now the problem is how can we know about these page numbers???

  • Extracting table data present in a section of MS word

    Posted by gb on 08/03/2012 10:48am

    How to get data from a table present in section of word doc?

  • How to get number of lines per page?

    Posted by dpreznik on 02/24/2011 05:54pm

    Deer Val, Could you please tell me how I can get number of lines of a random page? Or at worst, how I can get number of document's pages to divide the number of lines in the document by it and get the average number of lines per page? Thanks.

    • Figured it out

      Posted by dpreznik on 02/24/2011 06:37pm

      Never mind, I figured it out based on your GetLinesCount() method. Thanks!

  • how to change word doc's background color?

    Posted by ship1912 on 01/28/2011 12:20pm

    Thank you!

  • Tracking SaveAs events in MS Word using Automation class

    Posted by dinakara on 08/26/2010 12:56pm

    Dear Val Golovlev
      Thanks for for posting two interesting articles on  Automation Class of Microsoft Word and Excel in Codeguru.  After going through your article, I was wondering, would it be possible to track certain events like Save As events in Microsoft Office word/Excel/powerpoint  from my MSVC application.
    Basically, I would like to trace the source and Destination Paths of the files that is being saved using "Save As" menu option in the MS Word/Excel from my MSVC application 
    I appreciate your valuable suggestions/ help or sample code...
    Thanks in advance
    Dinakara K

  • Loading, Please Wait ...

  • You must have javascript enabled in order to post comments.

Leave a Comment
  • Your email address will not be published. All fields are required.

Most Popular Programming Stories

More for Developers

RSS Feeds

Thanks for your registration, follow us on our social networks to keep up-to-date