Call non-registered .NET dll from Excel VBA

前端 未结 3 1286
北海茫月
北海茫月 2020-12-19 07:58

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 deployed in the same directory without any COM regis

相关标签:
3条回答
  • 2020-12-19 08:23

    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 讨论(0)
  • 2020-12-19 08:39

    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.)

    0 讨论(0)
  • 2020-12-19 08:39

    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.

    0 讨论(0)
提交回复
热议问题