Problem accessing Worksheet property of Range object (C++)

M

Me:)

I get access violation while executing the program shown below. It happens
inside excel.tli in the inline Excel::RangePtr Excel::_Worksheet::GetCells (
) function. If I use any other method of pSheet2 same exception happens so it
looks like the p->Worksheet property produced an invalid result.

I use Visual Studio 2008 and tried this program with both Excel 2003 and
Excel 2007 under Vista and Excel 2003 under Windows XP. If anyone can point
out what is causing the exception and how to access Worksheet property of
Range object successfully I will be very grateful.

#import "C:\\Program Files\\Common Files\\Microsoft
Shared\\OFFICE11\\MSO.DLL" \
rename( "RGB", "MSORGB" )

#import "C:\\Program Files\\Common Files\\Microsoft
Shared\\VBA\\VBA6\\VBE6EXT.OLB"

#import "C:\\Program Files\\Microsoft Office 2003\\OFFICE11\\EXCEL.EXE" \
rename( "DialogBox", "ExcelDialogBox" ) \
rename( "RGB", "ExcelRGB" ) \
rename( "CopyFile", "ExcelCopyFile" ) \
rename( "ReplaceText", "ExcelReplaceText" )

int APIENTRY _tWinMain(HINSTANCE, HINSTANCE,LPTSTR,int)
{
HRESULT hr = CoInitializeEx(NULL,
COINIT_APARTMENTTHREADED|COINIT_SPEED_OVER_MEMORY);

Excel::_ApplicationPtr pExcel;
pExcel.CreateInstance(_T("Excel.Application"));
Excel::_WorkbookPtr pBook = pExcel->Workbooks->Open(_T("test.xls"),
vtMissing, false);
Excel::_WorksheetPtr pSheet(pBook->Sheets->Item[1]);
Excel::RangePtr p(pSheet->Cells->GetItem(2, _T("B")));
p->Value = 123; // all ok here

// now I want to access another cell on the same worksheet that contains p
range
Excel::_WorksheetPtr pSheet2(p->Worksheet);
Excel::RangePtr p2(pSheet2->Cells); // Access Violation while executing
this line
Excel::RangePtr p3(p2->GetItem(5, _T("D")));

p3->Value2 = 321;

pBook->Close(true);
pExcel->Quit();

CoUninitialize();

return 0;
}
 

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