A Beginner’s Guide to calling a .NET Library from Excel

It’s actually very easy to call a .NET library directly from Excel, particularly if you are using Visual Studio 2005. You don’t need Visual Studio Tools for Office. However there doesn’t seem to be an easy guide on the internet anywhere. MSDN help is quite good on the subject, but can be a little confusing. This article is an attempt to redress the situation.

This article was updated 24th August 2007 to cover Excel 2007 and to clarify the issues with intellisense.

A Basic Walk Through

We’ll start by walking through a very basic example. We’ll get Excel to call a .NET method that takes a string as input (for example “ World”) and returns “Hello” concatenated with that input string (so, for example, “Hello World”).

1. Create a C# Windows class library project in Visual Studio 2005 called ‘DotNetLibrary’. It doesn’t matter which folder this is in for the purposes of this example.

2. To call a method in a class in our library from Excel we need the class to have a default public constructor. Obviously the class also needs to contain any methods we want to call. For this walk through just copy and paste the following code into our default class file:

That’s it: if you look at existing articles on the web, or read the MSDN help, you might think you need to use interfaces, or to decorate your class with attributes and GUIDs. However, for a basic interop scenario you don’t need to do this.

3. Excel is going to communicate with our library using COM. For Excel to use a COM library there need to be appropriate entries in the registry. Visual Studio can generate those entries for us.

To do this bring up the project properties (double-click ‘Properties’ in Solution Explorer). Then:
i) On the ‘Application’ tab click the ‘Assembly Information…’ button. In the resulting dialog check the ‘Make assembly COM-visible’ checkbox. Click ‘OK’.
ii) On the ‘Build’ tab check the ‘Register for COM interop’ checkbox (towards the bottom: you may need to scroll down).

4. Build the library.

5. Now start Excel and open a new blank workbook. Open the VBA code editor:
i) In Excel 2007 this is a little difficult to find. You have to get the Developer tab visible on the Ribbon if it’s not already set up. To do this click the Microsoft Office Button (top left of the screen), then click Excel Options (at the very bottom). Check the ‘Show Developer tab in the Ribbon’ checkbox in the resulting Options dialog. Click OK. This adds ‘Developer’ to the end of the ribbon menu: click this. Then click the ‘Visual Basic’ icon at the left end of the ribbon.
ii) In earlier versions of Office (2003, XP, 2000) just go to Tools/Macro/Visual Basic Editor on the menu bar.

6. We now need to include a reference to our new library. Select ‘References’ on the Visual Basic Editor’s ‘Tools’ menu. If you scroll down in the resulting dialog you should find that ‘DotNetLibrary’ is in the list. Check the checkbox alongside it and click ‘OK’.

7. Now open the code window for Sheet1 (double click Sheet1 in the Project window). Paste the VBA code below into the code window for Sheet1:

8. Click anywhere in the code you’ve just pasted in and hit ‘F5’ to run the code. You should get a ‘Hello World’ message box.

Getting Intellisense Working in Excel

Whilst the VBA code above compiles and executes, you will discover that intellisense is not working in the code editor. This is because by default our library is built with a late binding (run-time binding) interface only. The code editor therefore doesn’t know about the types in the library at design time.

There are good reasons for only using a late-bound interface by default: with COM versioning libraries can become difficult with early-bound interfaces. In particular, if you change the early-bound interface by adding, for example, a method in between two existing methods you are likely to break existing clients as they are binding based on the order of the methods in the interface.

For similar reasons you are heavily encouraged to code your interface separately as a C# interface and then implement it on your class, rather than using the default public interface of the class as here. You then should not change that interface: you would implement a new one if it needed to change.

However, we can build our library to use early bound interfaces, which means intellisense will be available. To do this we need to add an attribute from the System.Runtime.InteropServices namespace as below:

If you change your code as above it will expose an ‘AutoDual’ interface to COM. This means it is still exposing the late-bound interface as before, but now also exposes an early-bound interface. This means intellisense will work.

To get this working:

1. Save your workbook and close Excel. Excel will lock the DotNetLibrary dll and prevent Visual Studio from rebuilding it unless you close it. Remember you need to save your new code module. If you are using Excel 2007 you will need to save as type Excel Macro-Enabled Workbook (*.xlsm). In earlier versions you can just save as a standard xls.

2. Go back into Visual Studio, change the DotNetClass as shown above, and rebuild the library.

3. Re-open your Excel spreadsheet. Once again if you are using Excel 2007 there is an extra step: you need to explicitly enable macros. A warning bar will appear beneath the ribbon saying the ‘Macros have been disabled’. Click the ‘Options’ button next to this, select ‘Enable this content’, and click OK.

4. Get the VBA code window up again (see item 5 above).

5. Excel can get confused about the interface changes unless you re-reference the library. To do this go to Tools/References. The DotNetLibrary reference should be near the top of the list now. Uncheck it and close the window. Now open the window again, find the library in the list, and re-check it (trust me, you need to do this).

6. Now run the code and it should still work (put a breakpoint in the routine and hit F5).

7. Enter a new line in the routine after the ‘MsgBox’ line, and type ‘testClass.’. When you hit the ‘.’ you should get an intellisense dropdown which shows that DotNetMethod is available. See below.

Let me re-iterate that this works and is fine for development, but for release code you are better off using the default late binding interfaces unless you understand the full versioning implications. That is, you should remove the ClassInterface attribute from your code when you do a release.

Deployment

In the example here we are using Visual Studio to register our .NET assembly on the workstation so that Excel can find it via COM interop. However, if we try to deploy this application to client machines we’re not going to want to use Visual Studio.

Microsoft have provided a command-line tool, regasm.exe, which can be used to register .NET assemblies for COM interop on client workstations. It can also be used to generate a COM type library (.tlb) separate from the main library (.dll), which is considered good practice in general.

As usual with .NET assemblies you have the choice of strong-naming your assembly and installing it in the GAC, or of not strong-naming it and including it in a local path. If you have strong-named your assembly and installed it in the GAC all you need to do is bring up a Visual Studio 2005 command prompt and run:

regasm DotNetLibrary.dll

If you have not strong-named your assembly you need to tell regasm.exe where it is so that it can find it to register it. To do this you need to run the command below, where c:\ExcelDotNet is the path where DotNetLibrary.dll can be found. This works fine, although it will warn you that you should really strong-name your assembly:

regasm /codebase c:\ExcelDotNet\DotNetLibrary.dll

Note that you can unregister an assembly with the /u option of regasm.

1. Using Visual Studio 2005 bring up the Properties window for the class library.

2. Go to the Debug tab and select the ‘Start external program’ option under ‘Start Action’. In the textbox alongside enter the full path including file name to Excel.exe for the version of Excel you are using (usually in Program Files/Microsoft Office/Office).

3. On the same Debug tab under ‘Command line arguments’ enter the full path including file name to your test workbook (the .xls file, or .xlsm if you are using Excel 2007). Once you’re done it should something like below::

4. Now put a breakpoint in the code (in our example the sensible place is in method DotNetMethod) and hit F5 in the .NET project. The .NET code should compile and Excel should start with your workbook opened. If you now run the VBA code to call the .NET library again, as above, you should find that the code will break at the breakpoint you set in the .NET code.

Possible Problem with these Examples

One problem we have had with these examples is that Excel can get confused about which version of the .NET Framework to load if you have more than one version installed. If this happens you will get an automation error when you try to instantiate .NET objects at runtime from Excel. The .NET types will appear correctly in the Excel object browser.

The workaround for this is to tell Excel explicitly that the version of the .NET Framework that you are using is supported. To do this create a text file called Excel.exe.config and put it in the same directory as Excel.exe itself. The file should contain the text below (with the version number replaced with the .NET Framework version you are using):

Hi, Nice easy-to-follow example. I am getting some problem trying to use the DLL on a machine where Visual Studio is not installed. The machine in question has .Net Framework 2. I have used “regasm /codebase /tlb” to register it. When I try to use the DLL’s method from MS Excel, I get an error message “Runtime error -2147024984(80070002) Automation error the system cannot find the file specified”

[…] 4th, 2007 by gobansaor Developing .NET DLLs that are to be used within an Excel VBA add-in is relatively easy to do. But the overhead of the COM managed interfaces can be a serious performance bottleneck if the .NET […]

Great Article. All my non static methods show up. However, how would i call a static C# method from VBA from Excel 2003. Any idea, i am struggeling not being the most sophisticated VBA programmer myself. THX! frank

I’ve been having a heckuva time with getting a managed Excel automation add-in without VBA. So far everything works on my development system but not on a deployment workstation – I found this blog because I’m looking into the Excel.exe.config issue – thanks for the details! My experience is documented on my blog at the link below. Maybe it will help someone here, and any assistance is welcome and appreciated.
remove.mungeNebula-RnD.com/blog/tech/2007/11/excel-tools1.html

I found this article very useful and informative. I am facing a problem i.e. I have to pass an array of strings form VBA to .Net assembly but I am getting a runtime error ‘450’. Any ideas?
Thanks in advance

Rich, A nice article – its simple and dare I say elegant.
Have you done this for Visual C++
I want to apply this to to a C++ library that I have written so I tried a small C++ example using a public ref class – a rework of your C# example.

But the C++ library does not show up in the VBA reference pane. I can get a C# library to pass the call to C++ but cannot see the C++.

An interesting symptom that I get is – I tried to use ILmerge to combine my C# small dll with my C++ dll. ILmerge complains that the C++ is not marked as managed code.Any thoughts would be very welcome.
Thanks
Rob

Excellent article – very clear.
I work in an office environment where we don’t have authorization to drop files into the Excel path. Is there any other way of telling Excel to use the 2.0 version of the framework? This article

says Excel should use the latest version by default, and you need a config file if you want to use an earlier version. However, this contradicts what I am seeing (and, apparently, the experience of many users on this board.)
Thanks for any info you can provide.

Alternative to Excel.exe.config
I actually found a solution to comment 22 (my own question). To recap – Excel really should use the latest installed version of .NET by default. If its not, it’s because something is telling it to use an older version. While using the Excel.exe.config is one solution, it may not be practical for many, and really only disguises the problem. The key as usual, is the registry. Specifically, check for:
HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\.NETFramework\policy\AppPatch\v2.0.50727.00000\excel.exe\{2CCAA9FE-6884-4AF2-99DD-5217B94115DF}
You should see a value named “Target Version” and Data = “v1.1.4322″
This is why Excel is using the older Framework. Removing or renaming this key should solve the problem.

I have had to do this several times but infrequently enough to have to look it up each time. This is by far the best guide I have ever seen about this. You have the dubious honour of being adding you to my “Useful” folder in my favourites. Thanks for making the effort to share.

Thank you for a very helpful post. FYI, I have been struggling with the first section (“A Basic Walk Through”), which mysteriously refused to work for a while, for reasons which seem to be related to .Net 3.5. I finally got it to work, by explicitly targeting .Net 2.0 (I am using Visual Studio 2008 / .NET 3.5 / Office 2003) and adding the Excel.exe.config file with matching version as you describe, and it worked.
Do you know if there are indeed specific issues related to .Net 3.5, or is it by sheer luck that I resolved the problem :) ?
Cheers,
Mathias

I’ve tried this with VS 2008/.NET 3.5/Office 2003 Pro and it still is balking. I’ve tried the targeting of .Net 2.0 and the Excel.exe.config file but still not working. I can see the type with intellisense but when i run the code, I get an object not found error (#91).

It is a very interesting article, however and I’m sure it is on the right path. I just need to find where I’ve wandered off of it.

Hi – Thanks so much for writing this article, I have had a hard time getting rid of the automation error I kept receiving due to my PC having several development environments installed. Your comment re. the Excel.exe.config file solved my problem! -Kenneth.

Thanks for the article and the links to other articles. The article on guidelines for com interop is particularly interesting.

I’ve just spent the past few hours trying to solve the same problem as Hongus posted earlier – denied access to the registry. I suspect it’s a VS2008 issue. In case anybody else has the same trouble, I solved it by, on loading VS2008 from the start menu, right-clicking the icon and selecting ‘Run as Administrator’.

I’m surprised this made a difference as I use an administrator account on my machine and have all the correct permissions for the registry. But it did the trick.

Also, another snag I encountered is that my VS2008 appears to set the ComVisible assembly attribute (in the AssemblyInfo file) to false, which hides all the code in the assembly from COM. Adding the attribute [ComVisible(true)] to the class overrides this.

Wonderfull article! This is all i want to start with. I was stuck for 2 days, referred to a lot of websites to find an answer. I got some idea that was complicated.The VB.NET class attribute ” _” gave a breakthrough. But this is even simpler. I wonder why i dint find this post so far.

Error 430 Class does not support Automation or does not support expected interface.

I have tried every trick in the book. I have followed this article to the T but is still get the above error. I am getting intellisense on the client machine, which means I can see the class, but it does not work.

Indeed, the best article in order to get started with C# Excel interaction. However, one minor point is missing. How to handle events if they fired in C#? Solution to that may allow to utilize multi threading in C# and do calls asynchroniously from Excel. So far I found nothing on this subject. Any suggestions?

I was able to implement this But the proble is when You try to retrun an array or Object It throw you and Exception on VBA side. Has anybody tried to implement that. Here;s My code.
using System;
using System.Collections.Generic;
using System.Text;
using System.Runtime.InteropServices;
using System.Reflection;

First of all Very good tutorial. It is clear you understand this very well, I’m hoping you also understand my similar problem and can point me in the right direction.

I am working with Visual Studio 2008 VB .net and Excel 2003 (and 2007 but that’s another problem)
I would like to know what it would take to build a “Self-Registering” dll which contains an or multiple object which can be placed within the excel sheets as ole objects.

Hi for those with the automation error. I think you will need to make sure your dll is in the same folder as your tlb and that your other assemblies that are not in the GAC are present in the folder when you run the regasm /codebase *name of dll* /tlb

I am trying to implement this in VS2008 with vb.net. I think that I have translated the code from CS to VB correctly but when I build I get an error message:

“A project with an Output Type of Class Library cannot be started directly. In order to debug this project, add an executable project to this solution which references the library project. Set the executable project as the startup project.”

Can anyone suggest how I might implement a vb.net class library in Excel VBA.

then I get a ‘run-time 430′ error (class does not support automation or expected interface), whenever I go to use a method (although I get intellisense, etc).

To add to the confusion, if I implement the Excel.exe.config file recommendation, then neither approach works (I then get ‘run-time error -214623576 (80131700)’).

Both of the above phenomenon occur with both Excel 2007 and Excel 2003. I am building using VS 2008 and .Net v3.5 SP1 (in the Excel.config.exe file I just reference v3.5). I have compiled this on two seperate machines, with the same results each time.

Thank you Rich. The [ClassInterface] attribute was missing, from the other examples I found, for getting Intellisense to work. FYI this just worked for me in Windows 7 Pro, DOTNET 4, Access and Excel 2007. Judging from the age of the original post we are still finding this useful. Thanks again!

Works!!!
I’m using Office 2010 VS2010 C# Express. I’m an engineer, not a programmer, but I’ve written a lot of code for my job.

1. Adrian’s comment above (shown below) came in handy.
“I’ve just spent the past few hours trying to solve the same problem as Hongus posted earlier – denied access to the registry. I suspect it’s a VS2008 issue. In case anybody else has the same trouble, I solved it by, on loading VS2008 from the start menu, right-clicking the icon and selecting ‘Run as Administrator’.
2. Then had to use the Intellisense version of the code that Rich Newman posted.

How can I create custom functions (built from VS C#) to add to Excel’s collection of functions?
-Noel

Thanks for this article, it helped me debug into my class library from my Excel client. I struggled for awhile, and finally learned that a space character in a folder name in the .xlsm file pathname was causing my error. Renamed the folder w/o the space, changed my Command Line Argument to the new path name, and it worked like a charm. Check for space characters in your command line argument path if you continue to have problems launching a workbook client from VS.

Thank-you for this article. I’ve been using this approach succesfully for a number of years and the Intellisense bit was new for me. I do have a problem now though – the approach has flat out stopped working since I upgraded to a new machine. I’m running Windows 7 64 bit Professional, VS2010, the 64 BIT version of Excel and .NET4 and I can’t instantiate the C# object from VBA. Everything else works just fine – I can add the reference to my type library and the the class and methods but my VBA code bombs with the dreaded “Active X Component can’t create object” error. There are two changes in my environment – O moved from .NET 3.5 to 4 and I moved to the Office 2010 64 bit app from the Office 207 32 bit (I’m pretty sure Office 2010 32 bit worked just fine too. I have tried the Excel.exe.config and registry key fixes to no effect. Anyone have any ideas?

Having the exact problem (64-bit-Office 2010 and with no problem on 32-bit). Still trying to figure out, but was able to achieve a temporary fix:

In my case, looks like the installer is replacing the tlb but not the dll.. deleting the dll, tlb & ‘Repair’ the program from Control Panel worked.While on some other machines, just manually registering the dll/tlb (Regasm.exe) worked.

[…] using a program called Regasm.exe. This is described in the “Deployment” section of A Beginner’s Guide to calling a .NET Library from Excel, but that guide appears to have been written in the days before Windows Vista and Windows 7, and […]

[…] Hi there, welcome to the board! Not necessarily. Excel [2010] runs VBA 7.0, and does not tie to the .NET framework, so you really don't have access to that class library. You would if the solution was built in Visual Studio, but not in VBA. There are some tricky ways to reference COM add-ins with VBA, but it must be set as ComVisible, and the ClassInterfaceType must match as well. While I haven't done much of this, I think the logic would be more to create your C/VB add-in, ensuring it's ComVisible, create your class(es) appropriately, then set a reference from VBA to your project as to access your class. Here is an example. And here is a walkthrough example. […]

Hi Thanks for the procedure. It helped me to some extent. but i am getting the following error “The system cannot find the file specified”. Please note that i am using DLL in another machine. i am able to use dll in the machine which i performed build but not in other machines.

Wow, this is step is really crucial. It cost me ages to figure it out:

“5. Excel can get confused about the interface changes unless you re-reference the library. To do this go to Tools/References. The DotNetLibrary reference should be near the top of the list now. Uncheck it and close the window. Now open the window again, find the library in the list, and re-check it (trust me, you need to do this).”