2014-11-03 22 views
1

我有一個C++函數,我在Excel 2013通過與VC2013內置一個DLL使用:如何通過DLL函數的參數將變量返回給Excel?

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崩潰我。什麼是正確的,優雅的方式來做到這一點?

回答

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) 
相關問題