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

Demonstration of OLE Automation of MS Word

By , 24 Feb 2002
 

Sample Image - word.jpg

Introduction

Here is a code sample of OLE Automation of Microsoft Word. The project accepts two folders as a Source path and Destination path. It opens each Document file in the Source Path and Checks for bookmarks which start with 'P', if it finds one, it will create a new file using the bookmarked contents.

Steps:

  1. Create a Dialog Project with MFC App Wizard, Tick the Automation support checkbox. Add 2 push buttons called 'Ellipsis1 and 'Ellipsis2'' and label them "source..." and 'destination...' (these are the browse buttons). Also add an 'Automate' button (this will launch the automation).

  2. Open Class Wizard, Goto Automation tab,

  3. Select Add Class

  4. Select From a type Library

  5. Select the file MSWORD*.OLD, where * can be anything depending on the Office installed on the machine.

  6. From the List select the classes _Application, _Document, Documents, Bookmarks, Bookmark, Range and Selection.

  7. Add two variables m_SourcePath & m_DestinationPath as CString to the Edit Boxes in the Dialog.

  8. For the Ellipsis1 'click' event add the following code. This code is called when the browse button is clicked and opens a 'Browse' dialog for the source path.
  9. void CWord1Dlg::OnEllipsis1() 
    {
        BROWSEINFO browseInfo;
        browseInfo.hwndOwner = NULL ;
        browseInfo.pidlRoot = NULL; 
        browseInfo.lpszTitle = "Enter The Source Path";   
        browseInfo.ulFlags = 0 ; 
        browseInfo.lpfn = NULL; 
        browseInfo.lParam = 0;  
    
        LPITEMIDLIST lpItemIDList;
        if ((lpItemIDList = ::SHBrowseForFolder(&browseInfo))!= NULL)
        {
            SHGetPathFromIDList(lpItemIDList,m_SourcePath.GetBuffer(256));
            UpdateData(FALSE);
        }    
    }
    
  10. For the Ellipsis2 click event add the following Code
    void CWord1Dlg::OnEllipsis2() 
    {
        BROWSEINFO browseInfo;
        browseInfo.hwndOwner = NULL ;
        browseInfo.pidlRoot = NULL; 
        browseInfo.lpszTitle = "Enter The Destination Path";   
        browseInfo.ulFlags = 0 ; 
        browseInfo.lpfn = NULL; 
        browseInfo.lParam = 0;  
    
        LPITEMIDLIST lpItemIDList;
        if ((lpItemIDList = ::SHBrowseForFolder(&browseInfo))!= NULL)
        {
            SHGetPathFromIDList(lpItemIDList,m_DestinationPath.GetBuffer(256));
            UpdateData(FALSE);
        }        
    }
    
    
  11. Add the following code to the 'Automate' Button
    void CWord1Dlg::OnAutomate() 
    {
        COleVariant m_True((short)TRUE), m_False((short)FALSE), 
                    m_Long((long)DISP_E_PARAMNOTFOUND, VT_ERROR);
    
        long startPos,endPos,m_LoopVar;
    
        BOOL m_FoundTheFile;
        
        CString m_FileName;
    
        UpdateData(TRUE);
        if(m_SourcePath=="" || m_DestinationPath =="")
        {
            MessageBox("Either Source Or Destination Path is Invalid",
                       "Easy Split Error",MB_ICONINFORMATION);
            return;
        }
    
        _Application appObj;
    
        if(!appObj.CreateDispatch("Word.Application"))
        {
            AfxMessageBox("Coud Not Create The Application Object");
        }
    
        appObj.SetVisible(FALSE);
    
        Documents docsObj(appObj.GetDocuments());
    
        _Document docObj,tempDocObj;
    
        CFileFind m_FileFind;
    
        m_FoundTheFile = m_FileFind.FindFile(m_SourcePath+"\\*.doc");
    
        while(m_FoundTheFile)
        {
            m_FoundTheFile=m_FileFind.FindNextFile();
    
            docObj.AttachDispatch(docsObj.Open(COleVariant(m_FileFind.GetFilePath()),
                                  m_False,m_False,m_False,m_Long,m_Long,m_False,
                                  m_Long,m_Long,m_Long  ));
    
            Bookmarks m_Books(docObj.GetBookmarks());    
    
            Bookmark m_Book;
    
            Selection selObj(appObj.GetSelection());
    
            startPos=0;
            endPos=0;
    
            for(m_LoopVar=1;m_LoopVar<= m_Books.GetCount();m_LoopVar++)
            {
                startPos=endPos ;
        
                docObj.Activate();
            
                m_Book.AttachDispatch(m_Books.Item(COleVariant(m_LoopVar)));
    
                if(m_Book.GetName().GetAt(0)!='P')
    
                    continue;
    
                endPos= m_Book.GetEnd();
    
                selObj.AttachDispatch(appObj.GetSelection());
    
                selObj.SetRange(startPos,endPos);
    
                selObj.Copy();
    
                docsObj.Add(m_Long , m_Long );
    
                selObj.AttachDispatch(appObj.GetSelection());
    
                selObj.Paste();
    
                tempDocObj.AttachDispatch(appObj.GetActiveDocument());
    
                m_FileName.Format("%s%d.doc", m_DestinationPath+"\\"
                                  + m_FileFind.GetFileTitle(), m_LoopVar);
            
                tempDocObj.SaveAs(COleVariant(m_FileName),m_Long,m_False,
                                  COleVariant(""), m_True,COleVariant(""),
                                  m_False,m_False,m_False,m_False,m_False);
    
                selObj.Shrink();
    
                m_Book.DetachDispatch();
            }
        }
    
        tempDocObj.Close(m_Long,m_Long,m_Long);
    
        docObj.Close(m_Long,m_Long,m_Long);
    
        docsObj.Close(m_Long,m_Long,m_Long);
    
        appObj.Quit(m_Long,m_Long,m_Long);
    
        m_FileFind.Close();
    
        MessageBox("Completed Successfully","Easy Split",MB_ICONINFORMATION);
    }

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

Anishcv
Web Developer
United States United States
Member
A Developer from India. Concentrating on the Microsoft Technologies. VC++ and VB.
 

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board.
Search this forum  
    Spacing  Noise  Layout  Per page   
GeneralRe: Where to get documentation (more info) of these classesmemberJason Henderson17 Sep '03 - 5:06 
here[^]
 
"It is better to remain silent and be thought a fool than to open one's mouth and remove all doubt." - Abraham Lincoln
Jason Henderson
blog | articles

GeneralNot working on win2k (server) probablymemberdelfin26 Jun '02 - 2:13 
Not working on win2k
 
=======================
let's code !
Questiondoes this work on .net???memberhelp please9 May '02 - 12:07 
does this work on .net
AnswerRe: does this work on .net???memberJisys DevTeam12 Aug '03 - 12:31 
Yep, its possible to automate word in .NET (say C# or VB.NET) to generate reports.
 
Also, if you are interested in creating Word documents in .NET, you might want to look at WordReports at www.jisys.com
 
Hope that helps with what you are looking for.
 

 
Jisys DevTeam
 
Visit: www.jisys.com
 
WordReports - Create .NET reports in 3 lines of code - Developer component to replace Word automation.
 


GeneralRe: does this work on .net???sussAnonymous27 Aug '03 - 2:32 
This site is for free help, not for you to spam threads trying to sell a product that is clearly not worth $99 - code like this can be written easily if need be.
 
If you look at the internet simple code like yours is freely available.
 
Please do not spam these boards, with artificial advertising of your company and products.
 

Regards
paul
GeneralIssuesmemberperlmunger25 Feb '02 - 8:49 
The demo project is missing some files. I get the following error message while trying to build:
 
Compiling resources...
C:\dev\wordapp\Word1.rc(208) : fatal error RC1015: cannot open include file 'res\Word1.rc2'.
Error executing rc.exe.
 
The .ico file also appears to be missing.
 
It looks like you built the demo project with Word97. You should probably indicate that at the beginning so that people don't try to build it with Word 2000 and then get frustrated that it doesn't work. Also, the line that says "Select the file MSWORD*.OLD, where ....", shouldn't it be .olb and not .old?
 
Just a few pointers.
 
Best Regards,
 
-Matt
 
p.s. I'm sure you probably already know this, but there is info on MSDN at:
 
http://msdn.microsoft.com/library/default.asp?url=/library/en-us/dnoffdev/html/vsofficedev.asp
 
Just use Ctrl-F to search within the page for "Microsoft Word Automation". There are some good examples in there.

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

Permalink | Advertise | Privacy | Mobile
Web03 | 2.6.130523.1 | Last Updated 25 Feb 2002
Article Copyright 2002 by Anishcv
Everything else Copyright © CodeProject, 1999-2013
Terms of Use
Layout: fixed | fluid