bro*_*ng0 7 c++ dll excel vba excel-vba
我创建了一个包含名为"koduj"的函数的DLL.通过在Excel工作表单元格中使用它来调用此函数将返回所需的结果.从VBA调用"koduj"会返回错误的答案.
koduj需要两个参数:string nr_id和integer x1.它nr_id以ASCII表示形式计算字母的总和并添加x1.计算的总和不是返回的.
我按照这里的说明进行操作.
这是我的.cpp源文件:
#include<Windows.h>
#include<string>
using namespace std;
//Convert BSTR to wstring for convenience
wstring BSTR_to_wstring (BSTR text){
return wstring(text, SysStringLen(text));
}
//Calculate sum of letters in ASCII representation
int ASCII_sum (wstring ws){
int sum = 0;
for (unsigned int i = 0; i < ws.length(); i++)
sum += ws[i];
return sum;
}
//"koduj" function
int _stdcall koduj (BSTR nr_id, int & x1){
wstring ws_nr_id = BSTR_to_wstring(nr_id);
return ASCII_sum(ws_nr_id) + x1;
}
Run Code Online (Sandbox Code Playgroud)
这是我的VBA函数声明:
Declare Function koduj _
Lib "<dll_directory_and_full_name>" (ByVal x As String, ByRef y As Integer) As Integer
Run Code Online (Sandbox Code Playgroud)
通过写:
=koduj("aaa";1)
Run Code Online (Sandbox Code Playgroud)
在工作表单元格中,我得到了期望的结果(292)
调试此VBA代码:
Sub test()
Dim a As Integer
a = koduj("aaa", 1)
End Sub
Run Code Online (Sandbox Code Playgroud)
显示错误的结果(a = 24930)
我相信我的C++代码很好,因为从Excel的工作表调用时它可以正常工作.