Search code examples
c++excelcom

How to read and write Excel via COM object together with Excel instance manual operating


I am trying to read and write Excel via COM. And on the same time , I also want to modify the cell value manually . It seems there is an access conflict. How can I detect this conflict and avoid it/

The following is my code example. In the example, a do-loop will keep copying cell A1 value to cell A2. when I want to modify the value A1 manualy during COM running, error occurs and program exits.

//MicroSoft Office Objects
#import "C:\Program Files (x86)\Common Files\microsoft shared\OFFICE12\mso.dll"\
rename("DocumentProperties","DocumentPropertiesXL")\
rename("RGB","RBGXL")

//Microsoft VBA Objects
#import "C:\Program Files (x86)\Common Files\microsoft shared\VBA\VBA6\vbe6ext.olb"

//EXCEL application objects
#import "C:\Program Files (x86)\Microsoft Office\Office12\excel.exe" \
rename("DialogBox","DialogBoxXL") \
rename("RGB","RGBCL") \
rename("DocumentProperties","DocumentPropertiesXL")\
rename("ReplaceText","ReplaceTextXL") \
rename("CopyFile","CopyFileXL") \
exclude("IFont","IPicture") no_dual_interfaces

#include "stdafx.h"

#include <iostream>


int main(int argc, _TCHAR* argv[])
{


    //A try block is used to trap any errors in communication
    try
    {
        //Initialize COM interface
        CoInitialize(NULL);

        Excel::_ApplicationPtr XL;

        //Start the Excel Application
        XL.CreateInstance(L"Excel.Application");

        //Make the Excel Application visible, so that we can see it!
        XL->Visible=true;


        Excel::_WorkbookPtr pWorkbook;
        pWorkbook=XL->Workbooks->Open(L"D:\\test.xls");

        //Get a pointer to the active worksheet     
        Excel::_WorksheetPtr pSheet = pWorkbook->Sheets->Item[L"Sheet1"];

        //Get a pointer to the cells on the active worksheet
        Excel::RangePtr pRange = pSheet->Cells;



        pRange->Item[1][1]=20;

        int a;

        //perform a loop to copy value in A1 to A2
        do
        {
            a=pRange->Item[1][1];
            std::cout<<"a="<<a<<std::endl;
            pRange->Item[2][1]=a;
        }while(a>0);

    }
    //If a communication error is thrown, catch it and complain
    catch(_com_error)
    {
        std::cout<<"COM error "<<std::endl;
    }

    //Finally Uninitialise the COM interface

    CoUninitialize();

    //Finish the C++ program

    return 0;
}

Solution

  • I have solved this problem by using COM directly but not OLE after reading freddie1's article http://www.cplusplus.com/forum/windows/125996/

    Thanks anyway.