如何通过DLL函数的参数将变量返回到Excel?

时间:2014-11-03 16:54:53

标签: c++ excel vba dll

我有一个C ++函数,我通过使用VC2013构建的DLL在Excel 2013中使用:

double my_function(double input) {
//do something
return input*input;
}

在Excel VBA中,我包含以下函数:

Declare Function my_function Lib "DLL_with_my_function.dll" (ByVal input As Double) As Double

到目前为止,这种方法效果很好,但现在,我希望能够通过第二个参数返回第二条信息,例如错误代码。理想情况下,此错误代码可以通过debug.print输出到Excel中的单元格,或者至少输出到控制台。我坚持让整个事情发挥作用,并且已经有几次Excel崩溃了。这是我徒劳无功的尝试:

double my_function(double input, long *error_code) {
*error_code = 5;
return input*input;
}

#in Excel:    
Declare Function my_function Lib "DLL_with_my_function.dll" (ByVal input As Double, ByRef error_code as long) As Double

当我从工作表中调用该函数并指示一个单元格作为第二个参数时,Excel崩溃了。这样做的正确,优雅的方法是什么?

1 个答案:

答案 0 :(得分:1)

你不能将excel单元格作为长数字给c \ c ++,因为它不会自动转换

你可以这样做:

double my_function(double input, long *error_code) {
  *error_code = 5;
  return input*input;
}
//unless you don't want to build the long from bytes, you can use function to do so. 
long get_error_code(long* error_code ){
  return *error_code;
}
Excel中的

也声明了新函数:

Declare Function my_function Lib "DLL_with_my_function.dll" (ByVal input As Double, ByVal error_code as long) As Double
Declare Function get_error_code Lib "DLL_with_my_function.dll" (ByVal error_code as long) As Long

#now in the function you should allocate memory to the error code:
Dim hMem As Long, pMem As Long
#hMem is handle to memory not a pointer
hMem = GlobalAlloc(GMEM_MOVEABLE Or GMEM_ZEROINIT, 10) 
#pMem is your pointer     
pMem = GlobalLock(hMem)
#now you can call to my_function with the pointer:
retval = my_function(input, pMem)

#in VB there is auto cast so this will work: 
YourCell = get_error_code(pMem)
# Unlock memory make the pointer useless
x = GlobalUnlock(hMem)
# Free the memory
x = GlobalFree(hMem)