简体   繁体   中英

With Excel-DNA, how can an unspecified argument in an Excel add-in function call be distinguished from a missing one?

This question is about Excel-DNA's interpretation of calls to add-in functions within Excel.

In Excel, unspecified and missing arguments are not the same. This can be seen with the IF function (which has two required parameters followed by one optional parameter):

=IF() - this is invalid

=IF(,) - returns FALSE

=IF(,,) - returns 0

I'm using the ExcelIntegration.RegisterDelegates() method to register add-in functions within Excel, registering functions like this:

Delegate del = new Func<object, object, object, object>((a, b, c) => a.ToString() + " " + b.ToString() + " " + c.ToString());

var fnAttr = new ExcelFunctionAttribute { Name = "TestFunc", Category = "ExcelDnaTest", Description = "Test function", IsHidden = false };

var args = new List<object>();
args.Add(new ExcelArgumentAttribute { Name = "Arg1", Description = "First argument", AllowReference = true });
args.Add(new ExcelArgumentAttribute { Name = "Arg2", Description = "Second argument", AllowReference = true });
args.Add(new ExcelArgumentAttribute { Name = "Arg3", Description = "Third argument", AllowReference = true });

ExcelIntegration.RegisterDelegates(new List<Delegate> { del }, new List<object> { fnAttr }, new List<List<object>> { args });

This works as expected when all arguments are supplied:

=TestFunc("A", "B", "C") - returns "ABC"

However, the result for no arguments (ie three unspecified arguments) is the same as when either two or three missing arguments are provided (I don't know a way to supply a single missing argument):

=TestFunc()

=TestFunc(,)

=TestFunc(,,)

All of these return:

"ExcelDna.Integration.ExcelMissing ExcelDna.Integration.ExcelMissing ExcelDna.Integration.ExcelMissing"

For add-in functions analogous to Excel's IF function, these three formulas represent different function calls, but I can't find a way to tell them apart - Excel-DNA seems to supply its Missing value both for unspecified and missing arguments.

Q: Using Excel-DNA, how can I distinguish between the three calls to TestFunc() above?

You can't distinguish these cases in a user-defined function.

I don't believe the Excel C API (which Excel-DNA uses to implement the Excel -> .NET UDF interface) allows any UDF to see this distinction - there is no such concept as an 'unspecified' parameter in the C API - the XLOPER type in both of your cases is passed as xltypeMissing .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM