VBA can't find C# dll entry point

前端 未结 1 657
深忆病人
深忆病人 2021-01-21 17:52

I\'m creating a dll in C# which runs a simulation when a single function runSimulation() is called. This dll should be called from VBA, as certain parameter values are given as

相关标签:
1条回答
  • 2021-01-21 18:40

    I managed to call the 'runSimulation' function in VBA code, by exposing the Simulation class through an interface in C#:

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Runtime.InteropServices;
    
    namespace NSSimulation
    {
        public interface ISimulation
        {
            int runSimulation();
        }
    
        [ComVisible(true)]
        [ClassInterface(ClassInterfaceType.None)]
        public class Simulation : ISimulation
        {
            [ComVisible(true)]
            public int runSimulation()
            {
                return 0;
            }
        }
    }
    

    Then re-compile your project and export your rebuilt library with 'tlbexp.exe' from the Visual Studio command prompt:

    tlbexp.exe SimulationLib.dll /out:"SimulationLib.tlb" /win64
    

    Then open the Visual Basic editor in Excel and add a reference to 'SimulationLib.tlb' through "Tools->References->Browse". To verify

    Public x As New SimulationLib.Simulation
    
    Sub test()
       MsgBox x.runSimulation
    End Sub
    
    0 讨论(0)
提交回复
热议问题