I’m creating an Excel chart using C++. My problem is that I want to create multiple charts in same workbook.
This is my code:
CoInitialize(NULL);
Excel::_ApplicationPtr XL;
XL.CreateInstance(L"Excel.Application");
XL->Visible=true;
XL->Workbooks->Add(Excel::xlWorksheet);
Excel::_WorksheetPtr pSheet = XL->ActiveSheet;
pSheet->Name = "Name";
...
Excel::_ChartPtr pChart=XL->ActiveWorkbook->Charts->Add();
pChart->Name =arr1;
...
CoUninitialize();
… represents part of code where I fill table with data.
When I run it just once it creates new workbook with one worksheet and one plot. But when I want to put it inside for loop it opens multiple excel workbooks, all with pair sheet/plot. But I want them all to be inside one workbook.
Btw, I put for loop after this line: XL->Visible=true; and finish it before CoUninitialize();.
Thanks for the help!
Well, I don’t know the Excel COM API, and it’s been ages since I’ve used COM the last time myself, but, I think it’s obvious, that those statements
instruct Excel to add a new workbook (Workbooks is in the plural, and its Add methods is reasonable to assume to create a new one), in which you then create a new sheet.
Given this statement
I assume there should be also a
XL->ActiveWorkbook->Sheetswith a methodAdd(), that creates a new sheet in the current workbook, returning a pointer to it. So instead ofXL->Workbooks->AddI’d tryXL->ActiveWorkbook->Sheets->Add()to create a new sheet in the currently active workbook.Note that I didn’t read any documentation for this answer, this is just my assumptions from the naming of the methods and knowing the way Microsoft OOP schemes used to work (years ago).