How do I set an Excel RangePtr's Value = Value in C++? Currently I get HRESULT 0x80004005

0

I have an Excel RangePtr object, and I'm trying to convert its corresponding cells to values instead of formulas. I'm used to doing this in VBA where you can do this simply using r.Value = r.Value. In C++ I've tried an analogous approach:

rng->Value = rng->Value;

But when I run that, I get an exception from the HRESULT 0x8004005. There's nothing within the cell values that should cause Excel to choke; the values being returned ought to be just a _variant_t containing a SAFEARRAY of double values. So what am I doing wrong?

c++
excel
com
asked on Stack Overflow Aug 2, 2016 by Chel

2 Answers

0

D'oh. Looks like RangePtr.Value actually has to specify a XlRangeValueDataType constant, which isn't present in VBA:

rng->Value[Excel::XlRangeValueDataType::xlRangeValueDefault] = rng->Value;

Or I could have used the Value2 property instead of plain Value:

rng->Value2 = rng->Value2;

Hopefully this will be helpful to someone else who has this problem in the future.

answered on Stack Overflow Aug 2, 2016 by Chel • edited Aug 2, 2016 by Chel
0

After painful search I came to the same conclusion, and use value[Excel::XlRangeValueDataType::xlRangeValueDefault] to get the equivalent of range.value in c# or vb in C++/CLI. Let me see if that works... Yes, that's the solution, it works!

Btw: if you ever need to use the Range::Address property you can use the style Address[false, false, Excel::XlReferenceStyle::xlA1, Type::Missing, Type::Missing]; with the appropriate parameters, of course.

Furthermore, regarding the value property, I found out that the presence of a cell value can be checked by: Value[Excel::XlRangeValueDataType::xlRangeValueDefault] != nullptr

Frequently, typecasts a la "safe_cast<Excel::Range^>" and "safe_cast<Excel::Workbook^>" are also helpful. The whole subject matter of using Excel automation with C++/CLI is poorly documented.

answered on Stack Overflow Feb 6, 2021 by Jens Kluge • edited Feb 6, 2021 by Jens Kluge

User contributions licensed under CC BY-SA 3.0