Wednesday, April 2, 2008

Create and register ADDin to Use in Excel

namespace NAddIn
{
[ClassInterface(ClassInterfaceType.AutoDual)]
public class Functions
{
public Functions()
{
}

public double Add2(double v1, double v2)
{
return v1 + v2;
}

[ComRegisterFunctionAttribute]
public static void RegisterFunction(Type t)
{
Microsoft.Win32.Registry.ClassesRoot.CreateSubKey(
"CLSID\\{" + t.GUID.ToString().ToUpper() +
"}\\Programmable");
}

[ComUnregisterFunctionAttribute]
public static void UnregisterFunction(Type t)
{
Microsoft.Win32.Registry.ClassesRoot.DeleteSubKey(
"CLSID\\{" + t.GUID.ToString().ToUpper() +
"}\\Programmable");
}
}
}

Build the NAddIn project to create bin\debug\NAddIn.dll.
Test the Add-In in Excel:
Open a new workbook in Excel.
Select Tools, Add-Ins, Automation.
NAddIn.Functions should be listed - select it. OK.
In a cell, type =Add2(3,4)
The cell should display 7.
To register the .dll after moving it, run regasm with the /codebase flag (typically as c:\WINDOWS\Microsoft.NET\Framework\v1.1.4322\RegAsm /codebase NAddIn.dll). You will get a warning about the assembly being unsigned - you can ignore this (or sign the assembly as documented).

No comments: