如何给Excel添加用户自定义的公式
如何给Excel添加用户自定义的公式
Excel允许我们自定义公式。过去的方法是通过一种叫XLL的特殊DLL来实现。但是XLL不能用托管代码来写。现在,用托管代码如何实现自定义公式呢?很简单,Excel支持一种叫自动化插件的技术,可以使用C#和VB.NET开发。
1. 打开Visual Studio 2005创建一个新的C#类库项目,取名叫AutomationAddIn。
2. 然后在Class1.cs中添加如下的代码
using System;
using System.Runtime.InteropServices;
using Microsoft.Win32;
namespace AutomationAddin
{
[ClassInterface(ClassInterfaceType.AutoDual), ComVisible(true)]
public class MyFunctions
{
public MyFunctions()
{
}
public double MultiplyNTimes(double Number1, double Number2, double TimesToMultiply)
{
double result = Number1;
for (double i = 0; i < TimesToMultiply; i++)
{
result = result * Number2;
}
return result;
}
[ComRegisterFunctionAttribute]
public static void RegisterFunction(Type type)
{
Registry.ClassesRoot.CreateSubKey(GetSubKeyName(type));
}
[ComUnregisterFunctionAttribute]
public static void UnregisterFunction(Type type)
{
Registry.ClassesRoot.DeleteSubKey(GetSubKeyName(type),false);
}
private static string GetSubKeyName(Type type)
{
string s = @"CLSID\{" + type.GUID.ToString().ToUpper() + @"}\Programmable";
return s;
}
}
}
3. 点击菜单Project-〉Properties,选中Build页,勾上Register for COM interop.
4. 编译整个类库项目
5. 启动Excel,调出Add Ins对话框(03,07有不同,见文后PS)
推荐文章 |
