using ExcelDna.Integration;
using ExcelDna.Registration;
using ExcelDna.IntelliSense;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Linq.Expressions;
namespace DemoUDFWithHandle
{
public class Calc // Assume this is a user-defined class
{
public double Value1 { get; set; }
public double Value2 { get; set; }
public Calc(double v1, double v2) { Value1 = v1; Value2 = v2; }
public double Sum() { return Value1 + Value2; }
}
public static class MyUDF
{
[ExcelFunction(Description = "Creates a Calc object and returns it as a handle.")]
[return: ExcelHandle] // Mark return value as a handle
public static Calc MyCreateCalc(double d1, double d2)
{
return new Calc(d1, d2);
}
[ExcelFunction(Description = "Takes a Calc handle and returns its sum.")]
public static object MyCalcSum([ExcelHandle] Calc c) // Mark parameter as a handle
{
if (c == null) return ExcelDna.Integration.ExcelError.ExcelErrorValue;
return c.Sum();
}
[ExcelFunction(Description = "Creates an integer and returns it as a handle.")]
[return: ExcelHandle]
public static int MyCreateSquareIntObject(int i)
{
return i * i;
}
[ExcelFunction(Description = "Takes an integer handle and prints its info.")]
public static string MyPrintIntObject([ExcelHandle] int i)
{
// Note: The value 'i' here is the actual int, resolved from the handle by Excel-DNA
return $"IntObject (from handle) value = {i}";
}
}
class XllAddIn : IExcelAddIn
{
public void AutoClose()
{
}
public void AutoOpen()
{
var targetFunctions = ExcelRegistration.GetExcelFunctions();
targetFunctions.RegisterFunctions();
IntelliSenseServer.Install();
}
}
}
////// .dna ///////
<?xml version="1.0" encoding="utf-8"?>
<DnaLibrary Name="DemoUDFWithHandle Add-In" RuntimeVersion="v4.0" xmlns="
http://schemas.excel-dna.net/addin/2020/07/dnalibrary">
<ExternalLibrary Path="DemoUDFWithHandle.dll" ExplicitExports="false" LoadFromBytes="true" Pack="true" IncludePdb="false" ExplicitRegistration="true"/>
</DnaLibrary>