Working with Excel 2003 from a Visual C++ program

Z

zm01

I am quite new to programming. Despite that I have to write a C++ program
that opens an .xls workbook, selects a specified worksheet and puts data in
specified cells of the worksheet. I have found a document in the Internet
that describes how to use the Excel COM model. Based on this I created a
program that is able o open a specified .xls workbook and put data in
specified cells in the active sheet. However I do not know how to select a
specified worksheet so that I do not put the data in the worksheet that ust
happens to be active when opening the workbook. How to do that?

Here is the code that does what I described:

CoInitialize(NULL);
Excel::_ApplicationPtr xl;
xl.CreateInstance(L"Excel.Application");
xl->Visible = true;
xl->Workbooks->Open(L"C:\\Documents and Settings\\WRO00724\\my
documents\\Visual Studio
2008\\Projects\\Project1\\Excel3\\Excel3\\Example.xls");
Excel::_WorksheetPtr pSheet = xl->ActiveSheet;
Excel::RangePtr pRange = pSheet->Cells;
pRange->Item[2][1] = 0.86;
pRange->Item[3][1] = "test";

What program lines should I include in order to be able to specify the
particular worksheet the data have to go to?
 
Z

zm01

I have finally found a solution:

Excel::_WorksheetPtr myWrks(xl->Worksheets->Item["Sheet2"]);
myWrks->Activate();


So my program looks now this way:

CoInitialize(NULL);
Excel::_ApplicationPtr xl;
xl.CreateInstance(L"Excel.Application");
xl->Visible = true;
xl->Workbooks->Open(L"C:\\Documents and Settings\\WRO00724\\my
documents\\Visual Studio
2008\\Projects\\Project1\\Excel3\\Excel3\\Example.xls");
Excel::_WorksheetPtr myWrks(xl->Worksheets->Item["Sheet2"]);
myWrks->Activate();
Excel::_WorksheetPtr pSheet = xl->ActiveSheet;
Excel::RangePtr pRange = pSheet->Cells;
pRange->Item[2][1] = 0.86;
pRange->Item[3][1] = "test";
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top