我在C#中创建一个DLL,该DLL在调用单个函数runsimulation()时运行模拟。该DLL应从VBA调用,因为在Excel中给出了某些参数值。这是我使用的代码。
c#:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Diagnostics;
using System.Windows.Forms;
using System.Runtime.InteropServices;
using RGiesecke.DllExport;
namespace Simulation
{
public static class Simulation
{
[ComVisible(true)]
[DllExport("runSimulation", CallingConvention = CallingConvention.Cdecl)]
[return: MarshalAs(UnmanagedType.SysInt)]
public static int runSimulation()
{
// Do simulation
return 0;
}
}
}
上面的代码被编译为具有x64作为平台目标的类库,并返回simulation.dll。
vba:
Public Declare Function runSimulation Lib "Simulation.dll" () As Long
Sub Run_DLL()
ChDir (ActiveWorkbook.Path)
Dim returnValue As Long
returnValue = runSimulation()
End Sub
运行视觉基本代码返回
运行时错误453:'找不到dll入口点在 simulation.dll'
试图调用runsimulation()。
作为参考:我尝试使用
运行[DllExport("runSimulation", CallingConvention = CallingConvention.StdCall)]
而是,但这也不起作用。我还尝试使用https://www.linkedin.com/grp/post/40949-258782989中给出的建议,但它给了我同样的错误。
我通过通过C#中的接口公开仿真类,在VBA代码中调用了'Runsimulation'函数。
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;
}
}
}
然后重新编译您的项目,并通过" tlbexp.exe"从Visual Studio命令提示中导出重建库:
tlbexp.exe SimulationLib.dll /out:"SimulationLib.tlb" /win64
然后在Excel中打开Visual Basic Editor,并通过" Tools-> coreences--> browse"添加" simulationLib.tlb"的引用。验证
Public x As New SimulationLib.Simulation
Sub test()
MsgBox x.runSimulation
End Sub