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