首页 > 解决方案 > 如何使用带有范围的 C++ 创建 XLL 文件?

问题描述

我想使用 c++ 创建用户函数 Excel。我创建了简单的用户函数,但我不知道如何使用参数是范围来创建它。

感谢您阅读并帮助我。

标签: c++

解决方案


要让用户定义函数 (UDF) 接受 XL 范围作为参数或返回变量,您需要在 c++ 中使用 XLOPER。这是 Microsoft Excel SDK 的一部分。我建议您从 SDK 中编译一些示例代码,然后从那里开始了解它。

这是 SDK 中的一个示例,其中 LPXLOPER12 用于 XL 2007+

/*
** fArray
**
** This example consists of two routines: fArray and xlAutoFree().
** This function creates an xltypeMulti containing eight values. It returns
** this array to Microsoft Excel with the xlbitDLLFree bit set. When
** Microsoft Excel is done with the values, it calls xlAutoFree(), which
** frees the memory that fArray() allocated.
*/

HANDLE hArray;

__declspec(dllexport) LPXLOPER12 WINAPI fArray(void)
{
    LPXLOPER12 pxArray;
    static XLOPER12 xMulti;
    int i;
    int rwcol;

    xMulti.xltype = xltypeMulti | xlbitDLLFree;
    xMulti.val.array.columns = 1;
    xMulti.val.array.rows = 8;

    //For large values of rows and columns, this would overflow
    //use __int64 in that case and return an error if rwcol
    //contains a number that won't fit in sizeof(int) bytes

    rwcol = xMulti.val.array.columns * xMulti.val.array.rows; 

    pxArray = (LPXLOPER12)GlobalLock(hArray = GlobalAlloc(GMEM_ZEROINIT, rwcol * sizeof(XLOPER12)));

    xMulti.val.array.lparray = pxArray;

    for(i = 0; i < rwcol; i++) 
    {
        pxArray[i].xltype = xltypeInt;
        pxArray[i].val.w = i;
    }

    //Word of caution - returning static XLOPERs/XLOPER12s is not thread safe
    //for UDFs declared as thread safe, use alternate memory allocation mechanisms

    return (LPXLOPER12)&xMulti;
}

__declspec(dllexport) void WINAPI xlAutoFree12(LPXLOPER12 pxFree)
{
    GlobalUnlock(hArray);
    GlobalFree(hArray);
    return;
}

推荐阅读