使用C ++中创建的DLL从Excel和VBA调用C ++函数 [英] Calling C++ function from Excel and VBA using DLL created in C++
问题描述
我创建了一个包含名为koduj的函数的DLL。通过在Excel工作表单元格中使用此函数来调用此函数,将返回所需的结果。从VBA调用koduj返回错误的答案。
I created a DLL containing a function named "koduj". Calling this function by using it inside an Excel worksheet cell returns the desired result. Calling "koduj" from VBA returns wrong answer.
koduj需要两个参数:string nr_id和整数x1。它计算ASCII表示中nr_id的字母的总和,并添加x1。
koduj needs two arguments: string nr_id and integer x1. It calculates sum of nr_id's letters in ASCII representation and adds x1. Calculated sum is than returned.
我按照以下指示找到此处
这是我的.cpp源文件:
Here's my .cpp sourcefile:
#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;
}
这是我的VBA函数声明:
Here's my VBA function declaration:
Declare Function koduj _
Lib "<dll_directory_and_full_name>" (ByVal x As String, ByRef y As Integer) As Integer
写:
=koduj("aaa";1)
在工作表单元格中获取所需的结果(292)
Inside a worksheet cell I get desired result (292)
调试此VBA代码:
Sub test()
Dim a As Integer
a = koduj("aaa", 1)
End Sub
显示错误的结果(a = 24930)
reveals wrong result (a = 24930)
我相信我的C ++代码是好的,因为它从Excel的工作表调用时正常工作。
I belive my C++ code is fine, as it works properly when called from Excel's worksheet.
推荐答案
从错误的大小,它是数值参数的错误 - 我会尝试更明确地声明测试VBA例程(可能是Integer)中的参数类型,并接受它作为C ++侧的特定类型(签名短,在
I'm guessing from the magnitude of the error that it's the numeric parameter that's going wrong - I would try more explicitly declaring the parameter type in your test VBA routine (probably Integer) and accepting it as that specific type on the C++ side (signed short, in that case).
有关这一切的一篇很好的Microsoft文章 http://msdn.microsoft.com/en-us/library/office/bb687915(v = office.15).aspx 。
There's a great Microsoft article about all this at http://msdn.microsoft.com/en-us/library/office/bb687915(v=office.15).aspx.
这篇关于使用C ++中创建的DLL从Excel和VBA调用C ++函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!