网站首页 新闻首页 网页设计图形动画软件编程网站开发办公软件操作系统数据库网络技术认证考试范文资料黑客攻防 书籍教程 进入论坛

如何给Excel添加用户自定义的公式

http://www.diybl.com/ 2008-1-16  网络 点击:  [ 评论 ]
文章搜索:    【点击打包该文章】

如何给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对话框(0307有不同,见文后PS)

文章整理:DIY部落 http://www.diybl.com (andyyoo)   【点击打包该文章】
如果图片或页面不能正常显示请点击这里 站内搜索:   

文章评论

请您留言