How can I call Range::Find from C++ without crashing Excel?

  • Thread starter Thread starter Aaron Queenan
  • Start date Start date
A

Aaron Queenan

I can call Range::Find from VBA - it works correctly, and requires only one
argument.

When I call it from C++, the function either throws an exception, or causes
a "Stack Corruption" error.

I am calling it with the following syntax:

Excel::_WorksheetPtr pWorksheet = Wb->Sheets->Item[1];

Excel::RangePtr pRangeSearch = pWorksheet->Cells;

Excel::RangePtr pRangeCurrent = pRangeSearch->Find("MKV", _variant_t(),
_variant_t(),
_variant_t(), _variant_t(), Excel::xlNext, _variant_t(),
_variant_t());

Is there anything I'm doing wrong?

Thanks,
Aaron Queenan.
 
In VBA, the method returns NOTHING (uninitialized object) if the target is
not found. Would that cause the error you are getting?
 
I don't know what's causing the error - Range::Find never returns, but about
10 seconds after calling it, I get either a stack frame corruption error
(something about the base pointer not being preserved across a function
call), or an exception. All of the arguments I'm passing as _variant_t()
are optional.

Aaron.

Tom Ogilvy said:
In VBA, the method returns NOTHING (uninitialized object) if the target is
not found. Would that cause the error you are getting?

--
Regards,
Tom Ogilvy

I can call Range::Find from VBA - it works correctly, and requires only one
argument.

When I call it from C++, the function either throws an exception, or causes
a "Stack Corruption" error.

I am calling it with the following syntax:

Excel::_WorksheetPtr pWorksheet = Wb->Sheets->Item[1];

Excel::RangePtr pRangeSearch = pWorksheet->Cells;

Excel::RangePtr pRangeCurrent = pRangeSearch->Find("MKV", _variant_t(),
_variant_t(),
_variant_t(), _variant_t(), Excel::xlNext, _variant_t(),
_variant_t());

Is there anything I'm doing wrong?

Thanks,
Aaron Queenan.
 
First of all for all the optional parameters that you don't use pass
vtMissing.
pRangeSearch->Find("MKV", vtMissing ...

Then make sure all the smart pointers wrap a valid interface pointer. You
should
always do something like this:
Excel::_WorksheetPtr pWorksheet = Wb->Sheets->Item[1];
ATLASSERT(pWorksheet != 0); // if called from atl code

Where do you use the given code? Could there be an issue with the calling
convention?
 
Back
Top