User-Defined Functions (UDF)
- 2 minutes to read
The Spreadsheet API provides the capability to create your own custom functions. Custom functions are available for spreadsheet calculations, and can be used in formulas in the same manner as built-in functions. The main difference is that custom functions are not saved in a workbook file. They should be added in code to the Workbook.CustomFunctions or the Workbook.GlobalCustomFunctions collection.
Add a custom function to the CustomFunctionCollection collection before loading a document.
If a worksheet contains a custom function that is not recognized by the workbook (or MS Excel), the "#NAME!" error is displayed after the cell containing the function is recalculated. To replace custom function definitions with the corresponding calculated values when saving a workbook, set the WorkbookExportOptions.CustomFunctionExportMode option to CustomFunctionExportMode.CalculatedValue.
A custom function called in a worksheet cell should not change the properties and characteristics of the worksheet. The IFunction.Evaluate method of the function has access to the EvaluationContext object, which provides information about the current worksheet and workbook. However, do not call methods or set properties that might perform the following actions:
- Insert, delete, or format cells;
- Move, rename, delete, or add sheets to a workbook;
- Add names to a workbook;
- Change the values of other cells.
A custom function is an object that exposes the ICustomFunction interface. To create a custom function, inherit from this interface and implement the required properties and methods. You should specify the IFunction.Name, and input IFunction.Parameters and IFunction.ReturnType. All calculations in a custom function are performed in the IFunction.Evaluate method. The IFunction.Volatile property specifies whether a cell that contains a custom function should be reevaluated every time a spreadsheet is recalculated.
By specifying the number and type of input parameters, you enable the workbook to validate the formula entered. If the formula is missing required parameters, an error message is displayed.
Custom functions are contained in a CustomFunctionCollection collection, which is available via the IWorkbook.CustomFunctions property. To use a custom function in a worksheet, add an instance of your function to the collection.
Function Arguments Dialog
This built-in dialog assists you with specifying the arguments of the custom function. To provide captions and text descriptions specific to the custom function, use the ICustomFunctionDescriptionsRegisterService service.
Review the How to: Create a Simple Custom Function article.