這幾天工作中在開發一個Excel插件,包含自定義公式,根據條件從資料庫中查詢結果。這次我們來做一個簡單的測試,達到類似的目的。
即在Excel 2010中添加一個Ribbon,包含4個自定義公式:僅僅是示例公式加減乘除。
最終效果:

<a href="http://files.cnblogs.com/brooks-dotnet/VSTO4/2011.08.30_Mr.Brooks_VSTO4_12_Excel2010x64_UDF_Ribbon.zip">測試代碼下載下傳</a>
1、解決方案包含兩個項目:
ExcelAddIn:Excel 插件
ExcelUDF:Excel 自定義公式
2、首先建立一個Excel 2010 Add-in項目:
3、添加一個可視化Ribbon:
4、在Ribbon的設計視圖中,設定下RibbonTab的屬性:
有個ControlIdType屬性,當設定為Custom時,此Ribbon顯示為Office中獨立的一項;當設定為Office時,此Ribbon作為Add-In中的一項出現。
5、在MyRibbon中添加一個Menu,在其中放置四個按鈕:
6、建立一個類庫項目:
7、編寫加減乘除四個函數和COM注冊、反注冊函數:
View Code
using System;
using System.Runtime.InteropServices;
using Microsoft.Win32;
namespace ExcelUDF
{
[Guid("E72F44C7-DD4A-4FA2-BC32-4EA9925749DB")]
[ClassInterface(ClassInterfaceType.AutoDual)]
[ComVisible(true)]
public class ExcelUDF
{
public int Add(int a, int b)
{
return a + b;
}
public int Subtract(int a, int b)
return a - b;
public int Multiply(int a, int b)
return a * b;
public int Divide(int a, int b)
return a / b;
#region COM Related
[ComRegisterFunction]
public static void RegisterFunction(Type type)
Registry.ClassesRoot.CreateSubKey(GetSubKeyName(type, "Programmable"));
var key = Registry.ClassesRoot.OpenSubKey(GetSubKeyName(type, "InprocServer32"), true);
key.SetValue("", Environment.SystemDirectory + @"\mscoree.dll", RegistryValueKind.String);
[ComUnregisterFunction]
public static void UnregisterFunction(Type type)
Registry.ClassesRoot.DeleteSubKey(GetSubKeyName(type, "Programmable"), false);
private static string GetSubKeyName(Type type, string subKeyName)
var s = new System.Text.StringBuilder();
s.Append(@"CLSID\{");
s.Append(type.GUID.ToString().ToUpper());
s.Append(@"}\");
s.Append(subKeyName);
return s.ToString();
#endregion
}
8、我安裝的是Excel x64,需要手動注冊自定義公式的程式集,為此在項目屬性中的Build Events中寫入批處理腳本來自動注冊:
%windir%\Microsoft.NET\Framework64\v4.0.30319\regasm /codebase "$(TargetPath)"
這樣在每次編譯成功後就會自動注冊該自定義公式。
9、在生成管理器中配置為 x64:
10、在Ribbon項目中添加調用自定義公式的代碼:
using Microsoft.Office.Tools.Ribbon;
namespace ExcelAddIn
public partial class RibbonDemo
private void RibbonDemo_Load(object sender, RibbonUIEventArgs e)
private void btnAdd_Click(object sender, RibbonControlEventArgs e)
Globals.ThisAddIn.Application.ActiveCell.Formula = "=Add()";
private void btnSubtract_Click(object sender, RibbonControlEventArgs e)
Globals.ThisAddIn.Application.ActiveCell.Formula = "=Subtract()";
private void btnMultiply_Click(object sender, RibbonControlEventArgs e)
Globals.ThisAddIn.Application.ActiveCell.Formula = "=Multiply()";
private void btnDivide_Click(object sender, RibbonControlEventArgs e)
Globals.ThisAddIn.Application.ActiveCell.Formula = "=Divide()";
11、修改Ribbon項目屬性,将 Excel設定為啟動的擴充程式:
12、編譯、運作,會調用Excel來打開,自動加載我們的插件ExcelAddIn:
13、激活自定義公式:
在【Developer】頁籤中點選【Add-Ins】,再點選【Automation】找到我們編寫的自定義公式,【OK】。
14、此時在Excel中就可以使用我們的公式了,EnjoyJ
小結:
本次把自定義Ribbon與自定義公式結合起來使用,具體細節可以參考源代碼,在我之前的VSTO 系列文章中也有介紹。
需要注意的是這種方法隻适用于Excel 2007、2010,2003不支援,關于Excel 2003的自定義菜單及自定義公式解決方案後面再介紹。
此外,隻有Excel 2010 x64需要用批處理腳本來注冊自定義公式,Excel 2010 x86不需要,會自動注冊。