[Last Call] Learn how to a build a cloud-first strategyRegister Now

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 396
  • Last Modified:

Creating an instance of an open Excel application

I'm writing a small app that uses OLE to communicate with Excel.  I know how to automate opening a new Excel application, adding a new workbook, and attaching an IDispatch pointer to Sheet #1.  How do I initiate communication with Sheet1 of Book1 of an Excel application  that is already open?  Any sample code appreciated.  Thanks.

0
dave140
Asked:
dave140
1 Solution
 
bobbymCommented:
Try using the compiler COM support of VC++ instead of the IDispatchDriver. The COM support uses smart pointers so that you do not have to worry about reference counting and such things. It also respresents better the Automation hierarachy.

In order to get the smart pointers for Excel include something like this in your .h file. This would generate the appropriate .tlh and .tli files for the smart pointers

#ifndef       _OFFICE_TYPE_LIBRARIES_INCLUDED
#define  _OFFICE_TYPE_LIBRARIES_INCLUDED
#undef RGB

#pragma warning( disable : 4146)  

#import  "c:\Msoffice\Office\MSO97.dll"
#import  "c:\Program Files\Common Files\Microsoft Shared\Vba\VBEEXT1.olb"
#import  "c:\Msoffice\Office\excel8.olb"
#endif


and somewhere in your .CPP file do something like this to run Excel.

Excel::_ApplicationPtr pExcelApp;
try
{
  Excel::_WorkbookPtr   pWorkbook;

  _variant_t vtIndex((long)1);
  _variant_t vtCell("A1");
  _variant_t vtValue("Some value");

  HRESULT hRes = pExcelApp.CreateInstance(_uuidof(Excel::Application));
  pExcelApp->Visible = Office::msoTrue;

  pWorkbook = pExcelApp->Workbooks->Open((LPCTSTR)"Some file name");

  Excel::SheetsPtr pWorksheets = m_pWorkbook->Worksheets;
  Excel::_WorksheetPtr pWorksheet  = pWorksheets->Item[vtIndex];
  pWorksheet->Range[vtCell]->Value = vtValue;
}
catch (_com_error err)
{
AfxMessageBox("COM Error Description:" + CString((LPCTSTR)err.Description()));
}

This code should write something in A1 in Excel (I am not sure I did not tested it but this is the idea :)). If you send me an e-mail (bobby_milanov@hotmail.com) I will send you a small C++ to make your life easier.

 Also note that you can also control when a smart pointer is linked to the object . If you call Release to a pointer this calls reelase to the underlying interface and then detaches the smart pointer.

Hope that helped :).

0

Featured Post

Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Tackle projects and never again get stuck behind a technical roadblock.
Join Now