Inside a c# UDF for excel 2007, I need to evaluate the value of Excel function parameters (don't ask why, long story).
Let's say we have this Excel function to evaluate :
=afunctionname("2009-01-01" ; "B4" ; "foo" ; concatenate("a";"b") )
My goal is to get a string with :
=afunctionname("2009-01-01" ; "value of B4 cell" ; "foo" ; "ab" )
I evaluate the value of the params thank to this snippet :
Object comObject = app.Evaluate(param); //app = Microsoft.Office.Interop.Excel.Application
String value = getValueFromComObject(comObject);
getValueFromComObject detail :
private static String getValueFromComObject(Object comObject) {
if ((comObject as Range) != null)
{
Range rge = ((Range)comObject);
switch (Type.GetTypeCode(rge.Value.GetType()))
{
case TypeCode.DateTime:
return ((DateTime)rge.Value).ToShortDateString();
default:
return rge.Value.ToString().Trim();
}
}
else
{
return comObject.ToString();
}
}
The fist and third params of our example directly return as String by application.Evaluate . The second param is return as a range and correctly managed thank to the type casting.
The problem is for the fourth param, I dont know witch cast type I have to apply on the evaluation of the concatenation function, it's obviously not a range and the toString() gives me the reference : -2146826273
Any idea?
Ok I found the problem :) !
First of all the return type is an Int32 and the return value correspond to the error code #value according to this page : How to know if a cell has an error in the formula in C#
Actually, the lengh of the Strings were too long for the concatenate function in eval mode, I have try in Excel it works but with eval it gives me an error. So I just had to reduce the lengh of each string in concatenate method (add more params) and it works.
Thank you all for your help.