I am posting this to elaborate on what are the options to run some C# functions (compiled) from VBA.
I have tried so far XLW and Excel DNA. Both of these enable you to build an .xll which you can reference from your Excel session to use (Excel DNA is better and easier. It is still supported also, whereas XLW hasn’t seen any update since .net 3 and requires VS2008 or 2005 with certain templates to run).
In my understanding, XLLs present a problem as they can’t be integrated into a spreadsheet and need to be separately loaded.
- Is there anyway to embed C# compiled code into a spreadsheet rather than Excel session to have VBA add ins working “standalone”/”out of the box”?
- Is it possible to load XLLs at runtime from VBA otherwise ? Are they any potential risks when doing so ?
- Any tips with regard to C#/VBA interop worth mentioning ?
Thank you !
One solution I’ve used in the past is to develop a VSTO 2005 .xls Document, convert it to an .xla, and use a technique similar to that described in this blog post from Paul Stubbs to get a reference to the COMVisible .NET code from VBA.
My preferred solution is to:
Define the COM interfaces to be implemented in .NET in IDL, and build a type library from it.
Import this type library into a .NET project, and create concrete classes that implement the required interfaces.
Return a factory class instance to VBA using the technique described in the linked blog post. Once VBA has this factory class instance, it can use it to get at all of the API.
By defining the COM interfaces manually using IDL, your VBA code will only need to reference these, rather than referencing typelibs generated from COM-visible .NET assemblies, which avoids a lot of versioning issues.