The following sample uses Microsoft Office Excel as the Automation
server. However, the technique that is illustrated can be used with other
Microsoft Office applications also.
Sample code
Excel has several methods that require an object as a
parameter. One method is the
Worksheet::Add method. The following sample code demonstrates passing a
COleDispatchDriver as a parameter to the
Worksheet::Add method.
// Start Excel.
_Application app;
COleException e;
if(!app.CreateDispatch("Excel.Application", &e)) {
char buf[80];
sprintf(buf, "Error on CreateDispatch(): %ld (%08lx)", e.m_sc, e.m_sc);
AfxMessageBox(buf, MB_SETFOREGROUND);
return;
}
// Make it visible.
app.SetVisible(TRUE);
// Add a workbook.
COleVariant covOpt((long)DISP_E_PARAMNOTFOUND, VT_ERROR);
Workbooks books(app.GetWorkbooks());
_Workbook book(books.Add(covOpt));
// Get sheets collection of book1.
Worksheets sheets(book.GetSheets());
// Get a reference to sheet1.
_Worksheet sheet1(sheets.GetItem(COleVariant((short)1)));
// encapsulate sheet1 object in a VARIANT.
VARIANT sheet1Var = {0};
sheet1Var.vt = VT_DISPATCH;
sheet1Var.pdispVal = sheet1.m_lpDispatch;
sheet1.m_lpDispatch->AddRef();
// Add a sheet just after sheet1. Excel's Sheets.Add method
// requires the 'After' parameter to be a sheet object, not
// a sheet name or index.
_Worksheet newSheet(sheets.Add(covOpt, sheet1Var, covOpt, covOpt));
AfxMessageBox("All done.", MB_SETFOREGROUND);
// Cleanup.
VariantClear(&sheet1Var);
book.SetSaved(TRUE);
app.Quit();