从自定义函数返回多个结果
可以从自定义函数返回多个结果,这些结果将返回到相邻单元格。 此行为称为溢出。 当自定义函数返回结果数组时,它称为动态数组公式。 有关 Excel 中的动态数组公式的详细信息,请参阅 动态数组和溢出数组行为。
下图显示了函数如何 SORT
溢出到相邻单元格中。 自定义函数还可以返回多个结果,如下所示。
若要创建动态数组公式的自定义函数,它必须返回值的二维数组。 如果结果溢出到已有值的相邻单元格中,公式将显示错误 #SPILL!
。
代码示例
第一个示例演示如何返回溢出的动态数组。
/**
* Get text values that spill down.
* @customfunction
* @returns {string[][]} A dynamic array with multiple results.
*/
function spillDown() {
return [['first'], ['second'], ['third']];
}
第二个示例演示如何返回向右溢出的动态数组。
/**
* Get text values that spill to the right.
* @customfunction
* @returns {string[][]} A dynamic array with multiple results.
*/
function spillRight() {
return [['first', 'second', 'third']];
}
第三个示例演示如何返回同时向下和向右溢出的动态数组。
/**
* Get text values that spill both right and down.
* @customfunction
* @returns {string[][]} A dynamic array with multiple results.
*/
function spillRectangle() {
return [
['apples', 1, 'pounds'],
['oranges', 3, 'pounds'],
['pears', 5, 'crates']
];
}
第四个示例演示如何从流式处理函数返回动态溢出数组。 结果会像第一个示例一样向下溢出,并根据 参数每秒 amount
递增一次。 若要了解有关流式处理函数的详细信息,请参阅 创建流式处理函数。
/**
* Increment the cells with a given amount every second. Creates a dynamic spilled array with multiple results
* @customfunction
* @param {number} amount The amount to add to the cell value on each increment.
* @param {CustomFunctions.StreamingInvocation<number[][]>} invocation Parameter to send results to Excel or respond to the user canceling the function. A dynamic array.
*/
function increment(amount: number, invocation: CustomFunctions.StreamingInvocation<number[][]>): void {
let firstResult = 0;
let secondResult = 1;
let thirdResult = 2;
const timer = setInterval(() => {
firstResult += amount;
secondResult += amount;
thirdResult += amount;
invocation.setResult([[firstResult], [secondResult], [thirdResult]]);
}, 1000);
invocation.onCanceled = () => {
clearInterval(timer);
};
}