I have found a way to call .NET 2 code directly from a VBA macro:
Dim clr As mscoree.CorRuntimeHost
Set clr = New mscoree.CorRuntimeHost
clr.Start
Dim domain As mscorlib.AppDomain
clr.GetDefaultDomain domain
Dim myInstanceOfDotNetClass As Object
Set myInstanceOfDotNetClass = domain.CreateInstanceFrom("SomeDotNetAssembly.dll", "Namespace.Typename").Unwrap
Call myInstanceOfDotNetClass.ExecuteSomeDotNetMethod
(To make this code work I hat to add references to mscoree.tlb and mscorlib.tlb to the Excel VBA using Tools -> References.. in Excel)
But this only works for .NET CLR 2 assemblies, up to .NET framework version 3.5.
Now I need to make it work with .NET 4.
I have understood that .NET CLR4 has introduced another, version agnostic, way of creating an instance of the runtime and I have also found a fairly easy code example written in C++: http://dev.widemeadows.de/2014/02/04/hosting-the-net-4-runtime-in-a-native-process/
But my Excel VBA skills are not enough to translate those few lines of code to a working VBA makro. Can anybody help me please?
Here is a canonical answer on the 3 main methods to call .Net from Excel (or VBA).
All three ways work in .Net 4.0.
1. XLLs
The 3rd party vendor Add-In Express offer XLL functionality, however its free and easy to use Excel-DNA the author is here https://stackoverflow.com/users/44264
Here is an extract from the Excel-DNA page: https://excel-dna.net/
2. Automation AddIns
This article by Eric Carter shows how to do it, the article is missing heaps of images so I am copy / pasting the entire article and have recreated the images for preservation.
REF: https://blogs.msdn.microsoft.com/eric_carter/2004/12/01/writing-user-defined-functions-for-excel-in-net/
Launch Excel and click the Microsoft Office button in the top left corner of the window.
Choose Excel Options.
Click the Add-Ins tab in the Excel Options dialog.
Choose Excel Add-Ins from the combo box labeled Manage. Then click the Go button.
Click the Automation button in the Add-Ins dialog.
3. Calling .Net from Excel VBA
REF: Calling a .net library method from vba
Using the code from the Automation.AddIn project we can easily call the MultiplyNTimes function from Excel VBA.
First Add a reference to the DLL from Excel, to do this you will need to be in the VB Editor. Press Alt + F11, then click Tools menu and References:
Select the AutomationAddIn DLL:
Add VBA code to call the .Net DLL:
And hey presto!
Finally there are some excellent MSDN articles about Excel and .Net by "Andrew Whitechapel" - google them
Here's your solution, tested for .NET 2.0 and .NET 4.0, 32 bit and 64 bit, courtesy of Soraco Technologies.
The solution proposed below uses late binding and does not require registration of the .NET assemblies.
Declarations
Add the following declarations to your project:
Initialization
You must initialize the m_homeDir variable to the path where the .NET assemblies are located.
For example, if you install the .NET assemblies in the same folder as the Excel or MS-Access files, you should initialize m_homeDir to:
Excel: m_homeDir = ThisWorkbook.Path
Access: m_homeDir = CurrentProject.Path
.NET Object Creation
Add the following code to your project.
Instantiate the .NET object
Now you are ready to instantiate your .NET object and start using it. Add the following code to your application:
The first argument is the full path to the .NET DLL.
The second argument is the fully qualified name of the requested type, including the namespace but not the assembly, as returned by the Type.FullName property.
Required DLLs
The solution requires deployment of 2 DLLs that are responsible for hosting the .NET CLR. The DLLs are expected to be deployed in the same folder as your Excel or MS-Access file.
The DLLs can be downloaded from Soraco’s web site: https://soraco.co/products/qlm/QLMCLRHost.zip
Licensing LGPL-2.1
We hereby grant you the right to use our DLLs as long as your application does not compete directly or indirectly with Quick License Manager. You can use these DLLs in your commercial or non-commercial applications.
The default policy is preventing the CLR 4 from excuting the legacy code from the CLR 2 :
To enable the legacy execution, you can either create the file
excel.exe.config
in the folder whereexcel.exe
is located:Or you can call the native function
CorBindToRuntimeEx
instead ofNew mscoree.CorRuntimeHost
:I'm not sure if this was just a coincidence or because I posted related question. SO showed me your question and I think I could also contribute something.
When working with VBA and DLL, most solutions that I've seen so far is telling me to register the DLL and make it com/gac visible. If you are doing this in your PC that's absolutely fine but if you are distributing your VBA application, you don't really want to install DLLs in their system. You might not have permission or you don't really want to go through install/uninstall process or messing with referencing issues.
However you can load dlls dynamically using some windows APIs.
DLL
Now the question is how to access .NET dll from vba? if your clients have mixed os architecture x86 x64 you need to handle this accordingly. Lets assume we are working on 32bit office/Excel.
If you create a .NET dll and would like to access it from VBA it will throw an error message similar to "Can't find the dll entry point". thankfully Robert Giesecke has created an abstract wrapper which will allow you to create simple DLL consumable via VBA.
A template can be found here.
All you have to do
Lets assume you have followed his template and created a test method as following.
and your unmanagedexport class:
Preparing to access the dll from vba side
Add the DLL to your root folder:
Now It's all about loading the dll and creating & accessing objects it in vba. that would be:
the output should be
Advantages I personally don't like installing and referencing dlls. By following above template, you don't need to reference anything, you don't need to install anything just load and work with your the DLL with full freedom.
NOTE: I assume the dll/.net code is yours and you can compile it again with above templates to.
I had success with above template and created a .NET non-blocking notifications for vba you can have a look here: non-blocking "toast" like notifications for Microsoft Access (VBA)