Click here to Skip to main content
Click here to Skip to main content

Create an Automation Add-In for Excel using .NET

By , 3 Aug 2004
 

Introduction

Excel versions 2002 (XP) and 2003 introduce the concept of an Automation Add-In. Automation Add-Ins allow public functions in COM libraries to act as User-Defined Functions (UDFs) in Excel, thus to be referenced directly from cell formulae.

This article provides a detailed walk-through of how to create an Automation Add-In for Excel using Visual Studio .NET.

Background

Some relevant knowledge base articles that discuss Automation Add-Ins are:

  • Q291392 - INFO: Excel COM Add-ins and Automation Add-ins.
  • Q285337 - How To Create a Visual Basic Automation Add-in for Excel Worksheet Functions.
  • Q278328 - XL2002: How to Mark an Automation Add-In Function as Volatile.

A commercial library that presents equivalent (and more) functionality, and makes this all very easy is ManagedXLL. However, this library is quite expensive and requires run-time licenses to distribute user code. It uses the native XLL API for creating an add-in to Excel, and thus also supports older versions of Excel.

The exact requirements for creating a COM server that can be used as an Automation Add-In are poorly documented, complicated by the fact that the default options in Visual Basic 6.0 seem to work perfectly.

When creating a COM library using .NET, an attempt to add the library as an Automation Add-In in Excel causes the error: “The file you selected does not contain a new Automation Server, or you do not have sufficient privileges to register the Automation Server”.

Here, I describe how to create an Automation Add-In in .NET, using C#. The techniques should apply to any .NET language.

There seem to be three tricks for implementing an Automation Add-In for Excel using .NET:

  1. The library needs to be registered for use through COM. This can be done by marking the project to ‘Register for COM Interop’ or by manual registration using RegAsm.exe.
  2. The ‘Programmable’ registry key needs to be added in the registry, under HKCR\CLSID\{xxx}\. This can be automated by adding appropriate ComRegisterFunction methods to the class.
  3. The class needs to be marked with the ClassInterface attribute, with value ClassInterfaceType.AutoDual (explicit interface implementations can work too). The default class interface that is generated is a dispatch interface - Excel seems to ignore the dispatch interface for Automation Add-Ins.

Walk-through

  1. Create the library:
    1. Create a new C# Class Library Project, called NAddIn.
    2. Select the project's properties; under ‘Configuration Properties’, ‘Build’, set ‘Register for COM Interop’ to True.
    3. Rename the class, add a namespace declaration, set the ClassInterface attribute of the class, and add a function to be used from Excel:
      using System;
      using System.Runtime.InteropServices;
      
      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");
              }
          }
      }
    4. Build the NAddIn project to create bin\debug\NAddIn.dll.
  2. Test the Add-In in Excel:
    1. Open a new workbook in Excel.
    2. Select Tools, Add-Ins, Automation.
    3. NAddIn.Functions should be listed - select it. OK.
    4. In a cell, type =Add2(3,4)
    5. 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).

History

  1. Initial version - 19 July 2004.
  2. Removed type library embedding instructions - 19 July 2004.
  3. Added ComRegisterFunction bits to automate registry changes - 30 July 2004.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here

About the Author

Govert van Drimmelen
Web Developer
South Africa South Africa
Member
No Biography provided

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board.
Search this forum  
    Spacing  Noise  Layout  Per page   
Questionhow to call this " Add2(3,4)" from another c#.2005 programmemembervishal nikam8316 Dec '08 - 20:44 
hii
i am using C#.NET 2005 my problem is that there is already an function developed some thing like " Add2(3,4)"
and now i have to call this from another C# program the code which i have used is given below ,my problem is that
the excell which is saved does not recognise the formula "Add2(3,4)" i am using excel 2007.
 

Excel.Workbooks objBooks;
Excel.Application objApp = (Excel.Application)new Microsoft.Office.Interop.Excel.ApplicationClass();
objBooks = objApp.Workbooks;
Excel.Workbook objBook = objBooks.Add(System.Reflection.Missing.Value);
Excel.Worksheet objSheet = (Excel.Worksheet)objBook.Worksheets.get_Item(1);
objSheet.Activate();
Excel.Range range = ( Excel.Range)objSheet.Cells[1, 1];
 
range.Formula = "=Add2(3,4)";
string FName = "";
if (SaveF.ShowDialog() == DialogResult.OK)
{
FName = SaveF.FileName;
 
object objMissing = System.Reflection.Missing.Value;
objBook.SaveAs((object)(FName), objMissing, objMissing, objMissing, objMissing, objMissing, Excel.XlSaveAsAccessMode.xlNoChange, objMissing, objMissing, objMissing, objMissing, objMissing);
objBook.Close(false, objMissing, objMissing);
 
objApp.Quit();
 

thanks...
AnswerRe: how to call this " Add2(3,4)" from another c#.2005 programmememberGovert van Drimmelen24 Dec '08 - 12:08 
I think the add-ins are not automatically loaded in the Excel application you create via Automation. You might need to add your add-in that contains the UDF explicitly, using Excel.AddIns..... (not sure how the object model looks.)
 
Also have a look at my newer project, ExcelDna (http://groups.google.com/group/exceldna) for making Excel Add-Ins and User-Defined Functions with .Net.
AnswerRe: how to call this " Add2(3,4)" from another c#.2005 programmememberjibin.mn5 Aug '10 - 1:22 
its due to regional ssetting problem.i am sure.....
General#REF!memberabi8011 Aug '08 - 4:26 
hi
 
i am trying to make a Excel 2007 UDF using vb .net 2003 to build an automation add in.
 
When i build the dll and add it to excel add in list through automation button, the dll gets added. the functions are available in the excel functions list.
 
However on using the function name in the cell, i get a #REF! error.
 
interestingly, if i use the fully qualified name fo the function, for example AutomationAddin.MyFunctions.MultiplyNTimes, the function executes and gives correct value. The function changes to 'MultiplyNTimes' immediately and gives error on editing again.
 
Can you please advise how to solve this.
 
Thanks
GeneralAddin in Excel 2002 getting registered - Add2 function is not shown in function browser in Excel 2002.memberMember 38506459 Jul '08 - 3:20 
I performed all the steps and build the solution.
The excel.exe.config file was also added in office11 folder.
 
The dll is getting registered.
The automation add in gets displayed in automation server
but then when the function is called in the excel cell it fails - #NAME?
 
Please guide me ..Urgent.
 

The same works well in excel 2003.
Questioncannot get .dll to work as addinmemberKl_Gl21 Jun '08 - 23:16 
Confused | :confused: Hi you all out there.
I am trying to create the addin as described in the article, and also copied the .dll to the same location as the excel, and tried to register it by running the regasm on it.
 
But I always get an error message saying
 
RegAsm error: Failed to load 'NAddIn.dll' because it is not a valid .Net assembly
 
I am using Windows Vista and Microsoft Visual C# 2008 Express Edition. Does anyone have a solution to the problem?
Thanks
 
Klaus G
AnswerRe: cannot get .dll to work as addinmembermike198924 Aug '10 - 11:28 
Be sure that you are using the regAsm tool for the .Net version that you built the assembly with.
 
For example if you are using VS2005, which compiles using the .NET 2.0 Frame work you would use this command:
 
C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\RegAsm /codebase NAddIn.dll
 

The NAddIn.dll file being located in the C:\WINDOWS\System32 directory
 
I hope that this helps I am pretty new to C# and the .Net framework
QuestionUsing dll as an add-in for a different machinememberwilliamw7 May '08 - 3:08 
I have written a dll in c# .NET 2.0 and have added the dll as an automation add-in for excel 2003 on my local machine. And it works great, thank you for the aid.
 
My problem is I want to use the dll as an add-in to excel 2003 on another machine. I have used regasm to register the dll on another machine and I have even been able to add the the dll as an automation add-in. Where it falls flat is that I cannot call any functions within excel on the other machine where I can call these functions on my local machine.
 
If anyone can help please let me know where I am going wrong.
 
Will

AnswerRe: Using dll as an add-in for a different machinememberwilliamw8 May '08 - 6:07 
It is now working. The solution is as follows.
 
Add the dll to the same location as Excel.exe.
 
Run regasm.exe /codebase .dll
 
This registers it correctly and the functions can now be used within excel.
 
Will

QuestionIs it possible to create functions that take a range/an array as input?memberJosefLagergren5 Mar '08 - 0:48 
Hi,
 
I got the function to work, but not when I try to make a function that takes a range. I've tried (among other things):
 
public double test(object input) { Excel.Range r = (Excel.Range)input; ...
public double test(object[] input) { Excel.Range r = (Excel.Range)input; ...
public double test(object[,] input) { Excel.Range r = (Excel.Range)input; ...
public double test(object input) { double[] r = (double[])input; ...
 
etc, etc, etc...
 
When I debug the input, I see that I get an exception...that I was missing the PIA - Microsoft.Excel.Interop...
 
Do I need this? Is there anyway to get this to work without it?

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Permalink | Advertise | Privacy | Mobile
Web01 | 2.6.130523.1 | Last Updated 4 Aug 2004
Article Copyright 2004 by Govert van Drimmelen
Everything else Copyright © CodeProject, 1999-2013
Terms of Use
Layout: fixed | fluid