如何通过DLL功能到Excel的一个参数返回一个变量?(How to return a variab

2019-10-21 05:19发布

我有我在Excel 2013通过与VC2013内置一个DLL使用C ++函数:

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

这种运作良好,到目前为止,但是,现在,我希望能够返回第二个资料片,说的错误代码,通过第二个参数。 理想的情况是该错误代码将必须是输出至细胞在Excel,或至少通过debug.print控制台的能力。 我停留在使整个事情的工作和有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崩溃我。 什么是正确的,优雅的方式来做到这一点?

Answer 1:

你只是不能给EXEL细胞只要数到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)  


文章来源: How to return a variable through an argument of a DLL function to Excel?
标签: c++ excel vba dll