How to return XLOPER (Excel Variable) to VBA directly from a c++ dll?

依然范特西╮ 提交于 2019-12-22 01:23:41

问题


I have no idea how to handle XLOPER type variable in VBA. There are plenty of web pages explaining the relationship between Xloper variable , c++ DLL and XLL add-in, however i need to write c++ function in a dll returning a xloper directly to VBA without XLL framework. (No need of User Defined Function since functions from the dll will be called by the VBA code - not by Excel users).

Indeed i'm coding a Excel VSTO and i need to call c++ code from it. I found that xloper variable are very useful for XLL so i would like to use this variable type in VBA/VB.Net directly. So is it possible?

  • my guess it that the xloper can be handled using variant type but i don't know how. i found this post :How can I marshall between XLOPER and VARIANT? but there is no clear answer.

EDIT :

sorry if i wasn't clear , so for instance i made this c++ function receiving a Int from excel and returning the same value plus 5 as a xloper variale to excel.

  _declspec(dllexport) xloper  _stdcall returnInt( int iVal)
 {
 xloper pxlval_ret;
 int a ;
 a =5 + iVal;

 pxlval_ret->xltype = xltypeInt;
 pxlval_ret->val.w =  a ;

 return pxlval_ret;
}

but i don't know how do call it in vba, Is the return variable a VARIANT?


回答1:


finally I read attentively the book "Excel Add-in Development in C / C++, 2nd Edition by Steve Dalton". It answers the question and provides source code for it. If you want to perform this operation you need to create a xloper wrapper, the xloper_to_v function which is par of xloper.cpp of the aforementioned book do this job. Due to copyrights, I can't publish here the whole code but just some lines of codes; i think it can give some useful insight:

bool xloper_to_vt(const xloper *p_op, VARIANT &var, bool convert_array)
{
VariantInit(&var); // type is set to VT_EMPTY

switch(p_op->xltype)
{
case xltypeNum:
    var.vt = VT_R8;
    var.dblVal = p_op->val.num;
    break;

case xltypeInt:
    var.vt = VT_I2;
    var.iVal = p_op->val.w;
    break;

case xltypeBool:
   // see in the book

case xltypeStr:
    // see in the book

case xltypeErr:
    // see in the book

case xltypeMulti:
    if(convert_array)
    {
        VARIANT temp_vt;
        SAFEARRAYBOUND bound[2];
        long elt_index[2];

        // see in the book

        xloper *p_op_temp = p_op->val.array.lparray;

        for(WORD r = 0; r < p_op->val.array.rows; r++)
        {
            for(WORD c = 0; c < p_op->val.array.columns;)
            {
            // see in the book
            }
        }
        break;
    }
    // else, fall through to default option

default: // type not converted
    return false;
}
return true;
}


来源:https://stackoverflow.com/questions/27473463/how-to-return-xloper-excel-variable-to-vba-directly-from-a-c-dll

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!