// ============================================================================= // B28 English — Custom function implementation (MyFunctions.cs) // B28 英文版 — 自定义函数实现(MyFunctions.cs) // ============================================================================= // // Key points: // 1. The containing class MUST be `public static`; methods MUST be `public static`. // 2. [ExcelFunction] is the Excel-DNA attribute: paste on a method to expose it as an Excel formula. // 3. [ExcelArgument(Name="...", Description="...")] gives parameters a friendly name + tooltip. // ============================================================================= using ExcelDna.Integration; // Excel-DNA core API namespace MyExcelAddIn { /// /// Custom function collection. /// The class MUST be `public static`. /// public static class MyFunctions { // ------------------------------------------------------------------------- // Example 1: add two numbers // Excel call: =MyAdd(10, 20) → 30 // ------------------------------------------------------------------------- [ExcelFunction( Name = "MyAdd", Description = "Add two numbers and return the result.", Category = "My Tools", IsVolatile = false)] public static double MyAdd( [ExcelArgument(Name = "Number1", Description = "First addend")] double x, [ExcelArgument(Name = "Number2", Description = "Second addend")] double y) { return x + y; } // ------------------------------------------------------------------------- // Example 2: concatenate strings // Excel call: =MyConcat("Hello", " ", "World") → "Hello World" // ------------------------------------------------------------------------- [ExcelFunction( Name = "MyConcat", Description = "Concatenate up to three strings into one.", Category = "My Tools")] public static string MyConcat( [ExcelArgument(Name = "Text1", Description = "First text")] string a, [ExcelArgument(Name = "Text2", Description = "Second text")] string b, [ExcelArgument(Name = "Text3", Description = "Optional third text")] string c) { string result = (a ?? "") + (b ?? "") + (c ?? ""); return result; } // ------------------------------------------------------------------------- // Example 3: wrap an RTD server // Excel call: =GetLivePrice() → refreshes every ~1 second // ------------------------------------------------------------------------- /// /// Wrap the RTD server MyExcelAddIn.MyRtdServer so users can call =GetLivePrice(). /// [ExcelFunction( Name = "GetLivePrice", Description = "Get a live price (RTD real-time-data sample).", Category = "My Tools - Realtime")] public static object GetLivePrice() { // XlCall.RTD(serverProgID, callbackParams, topic1, topic2, ...) // serverProgID = "Namespace.ClassName" return XlCall.RTD("MyExcelAddIn.MyRtdServer", null, "PRICE"); } } }