Search code examples
c++excelcom

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


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?


Solution

  • 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.