大家好,我的问题是,如何在一个XLL+程序中call另外一个XLL+中的函数。
我已经编好并运行成功了一个XLL+ user defined function,函数为sum1,在excel中加入这个add in以后,可以用sum1函数进行运算。现在我开始编写另外一个XLL,e.g.sum2,而在sum2程序中我想直接call sum1函数,然后由于两个函数在两个不同的XLL中,不能直接call,因此需要进行一定的处理才行。请问各位大牛有碰到过这种情况吗?有什么好的代码或者方法可以使用吗?
在网上查了一些,查到下列代码,是用evaluate和UDF function做的,但是这个貌似只适用于visual studio 2005,不适用于2012, 在Visual studio 2012下运行不出正确的结果,会显示#Name error
请各位大牛指导和指正!
// Function: CalDaysInYear2
// Purpose: Calls a function in another XLL
//{{XLP_SRC(CalDaysInYear2)
// NOTE - the FunctionWizard will add and remove mapping code here.
// DO NOT EDIT what you see in these blocks of generated code!
IMPLEMENT_XLLFN2(CalDaysInYear2, "RI", "CalDaysInYear2",
"DayCount", "Date & Time", "Calls a function in another XLL,"
" which returns number of days in a year according to the"
" day count", "Day count convention\000", "\0appscope=1\0",
1)
extern "C" __declspec( dllexport )
LPXLOPER CalDaysInYear2(short DayCount)
{
XLL_FIX_STATE;
CXlOper xloResult;
//}}XLP_SRC
static int xlfEvaluate = 257;
static int xlUDF = 255;
CXlOper xloName, xloRef;
int rc = 0;
xloName = "CalDaysInYear";
if (!rc)
rc = xloRef.Excel(xlfEvaluate, 1, &xloName);
if (!rc)
rc = xloResult.Excel(xlUDF, 2, &xloRef, &CXlOper(DayCount, 0));
return xloResult.Ret();
}
该回答引用ChatGPT
你可以通过以下步骤在一个XLL+程序中调用另一个XLL+程序中的函数:
在调用另一个XLL+程序中的函数的XLL+程序中,使用CXlWorkbook::LoadXll函数加载另一个XLL+程序。例如,如果要加载名为"sum1.xll"的XLL+程序,可以使用以下代码:
CXlWorkbook::LoadXll(L"sum1.xll");
然后,使用CXlOper类创建参数数组,以便传递给要调用的函数。例如,如果要调用名为"sum1"的函数并传递两个参数,可以使用以下代码:
CXlOper xloArgs[2];
xloArgs[0] = 1.0;
xloArgs[1] = 2.0;
最后,使用CXlFunction::Invoke函数调用要调用的函数。例如,如果要调用名为"sum1"的函数并传递两个参数,可以使用以下代码:
CXlOper xloResult;
CXlFunction::Invoke(L"sum1", xloResult, 2, xloArgs);
完整的调用另一个XLL+程序中的函数的示例代码如下:
#include "stdafx.h"
#include "xllplus.h"
using namespace xll;
int WINAPI xlAutoOpen()
{
// Load the other XLL+
CXlWorkbook::LoadXll(L"sum1.xll");
// Call a function in the other XLL+
CXlOper xloArgs[2];
xloArgs[0] = 1.0;
xloArgs[1] = 2.0;
CXlOper xloResult;
CXlFunction::Invoke(L"sum1", xloResult, 2, xloArgs);
// Return success
return 1;
}
请注意,在使用CXlWorkbook::LoadXll加载另一个XLL+程序之前,必须确保该程序已在Excel中加载。