How to easily create an Excel UDF with VSTO Add-in project

前端 未结 4 2109
日久生厌
日久生厌 2020-12-25 13:22

What I am trying to do is to create User Defined Functions (UDFs) for Excel using VSTO’s C# “Excel 2007 Add-in”-project type (since I just want to generate some general UDFs

4条回答
  •  佛祖请我去吃肉
    2020-12-25 13:35

    VSTO has no support for creating Excel UDFs. Automation Add-Ins can be created in .Net, and seem to be the Microsoft approved way of doing it.

    You should have a look at ExcelDna - http://www.codeplex.com/exceldna. ExcelDna allows managed assemblies to expose user-defined functions (UDFs) and macros to Excel through the native .xll interface. The project is open-source and freely allows commercial use. And you'll find that the performance of your .Net-based UDF is similar to native .xll add-ins for Excel. Excel 2007 features like the large sheet, long Unicode strings and multi-threaded recalculation are supported.

    With ExcelDna your function as posted above will be exposed to Excel with no VSTO - you can put to code into an xml-based .dna file or compile it to a .dll.

    The .dna file exposing your UDF would look like this:

    
       using System;
       using ExcelDna.Integration;
    
       public class MyFunctions
       {
          [ExcelFunction(Description="Calculate Stuff", Category="Cool Functions")]
          public static double HeronicCal(int a, int b, int c)
          {
             //first compute S = (a+b+c)/2
             double S = (a + b + c) / 2;
             double area = Math.Sqrt(S * (S - a) * (S - b) * (S - c));
             return area;        
          }
       }
    
    

    Update: These days, the easiest way to get started with Excel-DNA is to make a new Class Library project in Visual Studio, then add the 'ExcelDna.AddIn' package from NuGet. That makes a starter add-in - just paste your code and press F5 to run.

提交回复
热议问题