开发者

Call non-registered .NET dll from Excel VBA

开发者 https://www.devze.com 2023-03-04 01:55 出处:网络
I need to write a .NET dll that can be called directly from an Excel\'s VBA Module such that the dll and .xls are simply deploy开发者_Python百科ed in the same directory without any COM registration.

I need to write a .NET dll that can be called directly from an Excel's VBA Module such that the dll and .xls are simply deploy开发者_Python百科ed in the same directory without any COM registration.

Purpose of dll is to run algorithms implemented in C.

How should I proceed? Is this possible at all?


You don't explain what the role of .NET would be in your scenario. You can indeed call many C libraries directly from VBA using 'Declare Function'.

If you find .NET useful, and want to call your .NET library functions as user-defined functions (UDFs) from Excel, you can use Excel-DNA. It gives you an .xll add-in library that integrates your .NET library into Excel. You'd still have to open the .xll add-in somehow - either by File -> Open, by adding it as an Excel add-in, or automatically from some VBA in your workbook. But it needs no other registration.

From the .NET library you can call the C .dll functions using P/Invoke, add categories, function and argument descriptions to integrate into the function wizard etc.

(Disclaimer: I'm the developer of Excel-DNA.)


Have you seen this MSDN article? Basically you register functions from a DLL, not a DLL itself. I don't know if it is put very clear in the article, but the syntax is:

[Public | Private] Declare Function name Lib "libname" [Alias "aliasname"] [([arglist])] [As type]

where "libname" can contain full path e.g. "C:\tmp\algo.dll" or only a name e.g. "algo.dll". In the second case the local path will be searched for a matching binary.


If the DLL contains C functions then you should avoid .net and the CLR. That's a needless overhead.

Instead use a C compiler, MSVC for example, to build the DLL and export the functions you need from that DLL. Then import the DLL functions into VBA with Declare statements.

When you build the C functions into a DLL make sure that you use the __stdcall calling convention since that is the only option with Declare. You may also need to use a .def file when building the DLL to avoid name decoration.

A very simple example:

C

int __stdcall add(int a, int b)
{
    return a+b;
}

VBA

Public Declare Function add Lib "mylib.dll" (ByVal a As Long, ByVal b As Long) As Long
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号