Dealing with CVErr values in .NET is a very tricky subject. The problem is that .NET (rightfully) regards CVErr as obsolete with respect to error handling. CVErr values, however, are still used in Excel cells, so this is a rather large omission for Excel automation.
Fortunately, there is a workaround. The way to check for CVErr values is to examine the data type held by the cell. If the value held is typed as an Integer (Int32) then the value held is a CVErr. (Note that numerical values held in a cell are normally typed as Double, only CVerr values can come through as Integer.)
That is, at the simplest level, to test for a CVErr value, all you need to do is use the following function:
bool IsXLCVErr(object obj)
{
return obj is Int32;
}
If you need to check for a specific CVErr value (e.g., #N/A), then you would first check to make sure that the data type is an Integer (Int32) and then check the specific value held by the cell, according to this table:
- -2146826281 = #Div/0!
- -2146826246 - #N/A
- -2146826259 = #Name?
- -2146826288 = #Null!
- -2146826252 = #Num!
- -2146826265 = #Ref!
- -2146826273 = #Value!
For example, your code could look like this:
enum CVErrEnum : Int32
{
ErrDiv0 = -2146826281,
ErrNA = -2146826246,
ErrName = -2146826259,
ErrNull = -2146826288,
ErrNum = -2146826252,
ErrRef = -2146826265,
ErrValue = -2146826273
}
bool IsXLCVErr(object obj)
{
return (obj) is Int32;
}
bool IsXLCVErr(object obj, CVErrEnum whichError)
{
return (obj is Int32) && ((Int32)obj == (Int32)whichError);
}
I wrote a detailed two-part article on this a few years ago:
The articles are written for VB.NET, but the principles are exactly the same as for C#. You should have no trouble translating, but if you have any problems, then please ask. (Some day I hope to have the time to update this article for C#. If that happens at some point, I'll edit the post to include a link.)
Hope this helps!