如何通过DLL函数的参数将variables返回给Excel?

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

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

在Excel VBA中,我包含这样的function:

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

到目前为止,这个工作很好,但是现在,我希望能够通过第二个参数返回第二个信息,说错误代码。 理想情况下,这个错误代码可以输出到Excel中的单元格,或者至less通过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崩溃在我身上。 什么是正确的,优雅的方式来做到这一点?

你只是不能给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中也声明了新的function:

 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)