我想做的是使用VSTO的C#“Excel 2007 Add-in”项目类型为Excel创建用户定义函数(UDFs)(因为我只想生成一些通用UDF)。由于我只想学习基础知识(无论在这个阶段),所以我的代码如下:
using System;
using System.Collections.Generic;
using System.Text;
using System.Xml.Linq;
using Excel = Microsoft.Office.Interop.Excel;
using Office = Microsoft.Office.Core;
using Microsoft.Office.Tools.Excel;
using Microsoft.Office.Tools.Excel.Extensions;
using System.Runtime.InteropServices;
namespace ExcelAddIn1
{
public partial class ThisAddIn
{
private void ThisAddIn_Startup(object sender, System.EventArgs e)
{}
private void ThisAddIn_Shutdown(object sender, System.EventArgs e)
{}
//My UDF
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;
}
#region VSTO generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InternalStartup()
{
this.Startup += new System.EventHandler(ThisAddIn_Startup);
this.Shutdown += new System.EventHandler(ThisAddIn_Shutdown);
}
#endregion
}
}
代码编译通过,运行后Excel弹出一个新的电子表格,在Excel选项中查看“加载项”列表时,可以看到我的加载项(设置为“启动时加载”)。但是问题来了,当我尝试从Excel内部调用我的UDF时,Excel找不到该方法!
我想可能是因为我需要将我的方法标记为Excel UDF(使用方括号,就像编写Web服务时所做的那样 - “[WebService]”)。但我一直没有找到这个标记(而且由于我根本不确定我的猜测是否正确),这就是为什么我决定向SO等优秀的人寻求帮助。
所以我的问题基本上是 - 从我的代码位置出发,是否有任何简单的方法使我的UDF可供Excel使用?如果有,如何实现?
我真的很想坚持使用VSTO项目类型(Add-In、Workbook、Template),因为我的当前项目的总体目标是确定使用VS2010/Excel2007执行C# UDF是否具有可接受的速度。为了测试这一点,我正在Windows7RC上工作,并使用VS2010 beta1。