Click here to Skip to main content
15,868,016 members
Articles / Desktop Programming / MFC
Article

Demonstration of OLE Automation of MS Word

Rate me:
Please Sign up or sign in to vote.
3.00/5 (8 votes)
24 Feb 20021 min read 145.3K   23K   38   16
An article that demonstrates automation by showing how to split a MS-Word file based on Bookmarks

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


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


Comments and Discussions

 
GeneralAdding image... Pin
Omar.Pessoa28-Sep-07 4:38
Omar.Pessoa28-Sep-07 4:38 
QuestionI need to Append some text in the end? Pin
Sukar24-Jul-07 7:11
Sukar24-Jul-07 7:11 
Generalautomating embedded word document without MFC Pin
bjarki12-Jan-05 10:12
bjarki12-Jan-05 10:12 
GeneralRe: automating embedded word document without MFC Pin
thewizardcode19-May-05 8:44
thewizardcode19-May-05 8:44 
GeneralRe: automating embedded word document without MFC Pin
a.damm22-May-05 22:35
a.damm22-May-05 22:35 
GeneralRe: automating embedded word document without MFC Pin
AlexEvans9-Dec-05 14:58
AlexEvans9-Dec-05 14:58 
GeneralProblems with WordXP Pin
Alan-Lee Perkins13-Dec-04 23:32
Alan-Lee Perkins13-Dec-04 23:32 
QuestionIllegal chars for bookmark names? Pin
dansweeting16-Jan-04 6:37
dansweeting16-Jan-04 6:37 
GeneralRunning error on Win2k Advanced Server Pin
Kosan6-Jul-03 21:02
Kosan6-Jul-03 21:02 
GeneralWhere to get documentation (more info) of these classes Pin
Mahesh Perumal1-Jun-03 4:44
Mahesh Perumal1-Jun-03 4:44 
GeneralRe: Where to get documentation (more info) of these classes Pin
Jason Henderson17-Sep-03 5:06
Jason Henderson17-Sep-03 5:06 
GeneralNot working on win2k (server) probably Pin
delfin26-Jun-02 2:13
delfin26-Jun-02 2:13 
Questiondoes this work on .net??? Pin
9-May-02 12:07
suss9-May-02 12:07 
AnswerRe: does this work on .net??? Pin
Jisys DevTeam12-Aug-03 12:31
Jisys DevTeam12-Aug-03 12:31 
GeneralRe: does this work on .net??? Pin
Anonymous27-Aug-03 2:32
Anonymous27-Aug-03 2:32 
GeneralIssues Pin
perlmunger25-Feb-02 8:49
perlmunger25-Feb-02 8:49 

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.