VBA调用C++DLL

VBA调用C++DLL

C++DLL示例

以下建立了一个比较简单的C++的DLL,它的输入是一个字符串,两个double类型的变量,输出double类型的计算结果。
CPP代码:

#include "stdafx.h"
#include "test_excel.h"

double fun_property(const char *outProp, double inProp1Value, double inProp2Value)
{
    double val = inProp1Value + inProp2Value;
    return val;
}

头文件的设置如下,需要注意的是extern "C"是必须要加入的。

#pragma once

#ifdef DLLEXPORTS
#define DLLAPI extern "C" __declspec(dllexport)
#else
#define DLLAPI extern "C" __declspec(dllimport) 
#endif

DLLAPI double fun_property(const char *outProp, double inProp1Value, double inProp2Value);

编译DLL的时候,调用约定选择默认的__cdecl (/Gd)即可。

VBA调用说明

DLL的地址根据实际情况填写。
如果是64位的office,在声明DLL里的函数时,需要加上PtrSafe,且调用的是64位的DLL;如果是32位的office,在声明DLL里的函数时,不需要加上PtrSafe,且需要调用的是32位的DLL。
在声明DLL里的函数参数时,由于DLL里接受的是参数的值,所以需要在参数前加上ByVal,但如果DLL里接受的是参数的地址,则需要在参数前加ByRef。

Option Explicit

Private Declare PtrSafe Function fun_property Lib "E:\Tao\testExcel\testExcel\x64\Release\testExcel.dll" _
(ByVal outProp As String, ByVal inProp1Val As Double, ByVal inProp2Val As Double) As Double

Sub Funtiontest()
    Dim outPara As String
    Dim a As Double, b As Double, c As Double
    
    outPara = "test"
    a = 500000
    b = 1
    
    c = fun_property(outPara, a, b)

End Sub
  • 4
    点赞
  • 18
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值