HOW TO: Is there a way to reproduce the way Excel returns errors?

Reference: Q0020

Article last modified on 8-Nov-2005


The information in this article applies to:

  • XLL+ for Visual Studio .NET - 3, 4.1, 4.2, 4.3.1
  • XLL+ for Visual Studio 6 - 3, 4.1, 4.2, 4.3.1

Is there a way to reproduce the way Excel returns errors?

Question

Is there anyway to reproduce the way Excel returns errors? I can return a string with an error, such as "#VALUE!" but it is not formatted like an Excel error.

Answer

Return a CXlOper that contains an error code, such as xlerrValue, xlerrNA etc. You could return #VALUE! as follows:

CXlOper xloResult; 
xloResult = xlerrValue;
return xloResult.Ret();

You can also use a short-cut to return an error code, without instantiating a CXlOper to put it in, using the static method CXlOper::RetError(), thus:

return CXlOper::RetError(xlerrValue);
This technique is useful for a concise early exit from an add-in function, e.g.:
if (x < 0)
    return CXlOper::RetError(xlerrValue);
else if (x == 0)
    return CXlOper::RetError(xlerrDiv0);
// Continue with normal processing
...

See Also