xlladdins / xll

Excel add-in library
MIT License
104 stars 23 forks source link

How to return an vector of strings from a function? #12

Closed Ylikerroin closed 2 years ago

Ylikerroin commented 2 years ago

Hi Kalx and Thanks for your good work.

I have not succeeded to return vector of strings back to Excel. I enclose a body of my sample code below.
Hope to get hint how to proceed or even better corrected sample. BR Pauli

AddIn xai_GASstrings( Function(XLL????, "xai_Func_strings", "Func_strings") .FunctionHelp("Function should return 5 cells in vertical, no input ") .Category("Test") );

// typedef typename _FP12 xfp (structure for returning doubles) xfp* WINAPI xll_Func_strings(){

pragma XLLEXPORT

static FPX X; // this struct works for doubles not strings
std::string x[5] = { "string1", "string2", "string3", "string4", "string5"};
try{
    X.resize(5, 1);
    for (xword i = 0; i < 5; ++i){
        X(i, 0) = x[i];
    }
}
catch (exception& ex) {
    XLL_ERROR(ex.what());
    return 0;
}
return X.get();

}

keithalewis commented 2 years ago

The FP data type is only for arrays of numbers. Use the OPER data type for strings.

rmcrkd commented 2 years ago

This was a useful exercise for me, as I am quite new to the library. I do not understand why my example below does not work when the .Arguments call is removed, though.

    using namespace xll;

    xll::OPER WINAPI xll_gh12()
    {
    #pragma XLLEXPORT

        xll::OPER a(2, 1);
        a(0, 0) = "string0";
        a(1, 0) = "string1";

        return a;
    }

    AddIn xai_gh12(
        // Return cells, C++ name of function, Excel name.
        Function(XLL_LPOPER, "xll_gh12", "XLL.GH12")
        // Array of function arguments.
        .Arguments({
              Arg(XLL_LPOPER, "", "")
            })
        // Function Wizard help.
        .FunctionHelp("")
        // Function Wizard category.
        .Category("")
        // URL linked to `Help on this function`.
        .HelpTopic("")
        .Documentation(R"xyzyx(
    )xyzyx")
    );
keithalewis commented 2 years ago

You. Need to make a static and return &a. An LPOPER is an OPER*

rmcrkd commented 2 years ago

Thank you, @keithalewis ! For completeness:

    using namespace xll;

    xll::OPER* WINAPI xll_gh12()
    {
    #pragma XLLEXPORT

        static xll::OPER a(2, 1);
        a(0, 0) = "Hello,";
        a(1, 0) = "World!";

        return &a;
    }

    AddIn xai_gh12(
        // Return cells, C++ name of function, Excel name.
        Function(XLL_LPOPER, "xll_gh12", "XLL.GH12")
    );