Click here to Skip to main content
15,744,817 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Where is the problem with this code?
using namespace Excel;
int main(array<System::String ^> ^args)
    Excel::_ApplicationPtr pXL;
	pXL.CreateInstance(L"Excel.Application");//ok, starts excel
	pXL->PutVisible( 0, VARIANT_TRUE );//ok, makes excel visible
	WorkbooksPtr pBooks = pXL->Workbooks;//ok
	_WorkbookPtr pBook  = pBooks->Add((long)xlWorksheet);//ok, Opens Sheet1
	_WorksheetPtr pSheet = pXL->ActiveSheet;
	pSheet->Name = "My Sheet";//ok, renames Sheet1 to My sheet
	Range * pRange = pSheet->GetRange("A1","A1");//ok
	pRange->PutValue2( L"1000" );//not ok, crashes with this error
Attempted to read or write protected memory

Everything looks okay, but PutValue2 crashes. The similar code in MFC works fine.
Can anybody help me?

Thanks in forward.
Updated 16-Apr-11 10:54am
TweakBird 16-Apr-11 16:55pm    
Edited for spell correction & formatting.

1 solution

PutValue2 takes the address of an array - have a look at this[^]

The memory at 1000 is not in the program's addressable space, hence the error message
Share this answer
mr.abzadeh 16-Apr-11 20:11pm    
/* Why my browser doesnt show reply icon? So I have to add comment. */
Thats right. "1000" is a pointer to array of chars, and PutValue2 requires 1 argument of type VARIANT. I converted "1000" to VARIANT and It didnt work. I worked around and found that the reason is in the following code:

//This code caused pPrange->PutValue2(VARIANT *) to crach
Range * pRange = pSheet->GetRange("A1","A1");
pRange->PutValue2(VARIANT *);

//This code works well. It was extracted from the link above
pRangeAll = pSheet->Cells;
pRange = pRangeAll->Item[1][1];
pRange->PutValue2(VARIANT *);

I think the problem is in Range addressing, and I will examine it with care.
Another stange thing:
As you remember, Yesterday my compiler (VS2010) required PutVisible to pass two arguments( lcid, RHS ) and _Aplication->Visible = true; didnt compile.
But Now It has changed and PutVisible( lcid, RSH ) desn't compile(error: PutVisible doesn't have 2 arguments) and _Aplication->Visible = true; compiles. May be it's because my windows 7 was updated, buf I am not sure.
If you found an Idea about this strange behaviour, please post me at
Thanks for your pointing out, good luck

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900