Using Excel Built-in Functions on top of the UDF

2019-03-03 13:23发布

问题:

I don't know why for some reason the Excel built-in function =SUM() can't really sum up the results created by the custom UDF. It appears to always end up with 0.

For example, I have got a following UDF, called myUDF, which will return the number of items.

For the cell A1:
Formula: =myUDF('ItemA') Result: 10

For the cell B1:
Formula: =myUDF('ItemB') Result: 15

So When I do =Sum(A1:B1) and put the formula in cell C1, it won't return 25 but 0 instead.

I have tried to use some data formatting stuff (converting to numeric) but still no luck there. Has anyone here had similar issue before? Any ideas on the cause of it?

Thanks.

EDIT: Code Sample

        public object MyUDF(string id, string pk, string param1 = "", string param2 = "", string param3 = "", string param4 = "")
        {
            object result = null;
            string strFormula;

            double n = 0;
            DateTime dt;

            try
            {
                strFormula = buildFormula(id, pk, param1, param2, param3, param4);

                result = ws.getServiceResultsDataString(id, objUser, pk, param1, param2, param3, param4);

                if (double.TryParse(result.ToString(), out n)) 
                {
                    result = n;
                }
                else if (DateTime.TryParse(result.ToString(), out dt))
                {
                    result = dt.Date;
                }
                ws.Dispose();
                objUser = null;

            }
            catch (Exception ex)
            {               
            }
            finally
            {   
            }
            return result;
        }

回答1:

Is your UDF returning a number or a string that happens to contain numeric characters?

If I go into Excel and type in '10 (10, formatted as a string) and '15 (15, formatted as a string), and SUM() them, I get 0.

If I type 10 and 15 (formatted as numbers) and SUM() them, I get 25.

Some example code that reproduces the problem would allow us to answer for sure.