カスタム関数から複数の結果を返す

隣接するセルに返されるカスタム関数から複数の結果を返すことができます。 この動作はスピルと呼ばれます。 カスタム関数が結果の配列を返す場合、動的配列式と呼ばれます。 Excel の動的配列数式の詳細については、「 動的配列とスピルされた配列の動作」を参照してください。

次の図は、関数が SORT 隣接するセルにスピルダウンする方法を示しています。 カスタム関数は、このような複数の結果を返すこともできます。

複数の結果を複数のセルに表示する SORT 関数のスクリーン ショット。

動的配列式であるカスタム関数を作成するには、値の 2 次元配列を返す必要があります。 結果が既に値を持つ隣接するセルにスピルすると、数式にエラーが表示 #SPILL! されます。

コード サンプル

最初の例は、スピルダウンする動的配列を返す方法を示しています。

/**
 * Get text values that spill down.
 * @customfunction
 * @returns {string[][]} A dynamic array with multiple results.
 */
function spillDown() {
  return [['first'], ['second'], ['third']];
}

2 番目の例は、右にスピルする動的配列を返す方法を示しています。

/**
 * Get text values that spill to the right.
 * @customfunction
 * @returns {string[][]} A dynamic array with multiple results.
 */
function spillRight() {
  return [['first', 'second', 'third']];
}

3 番目の例は、下と右の両方をスピルする動的配列を返す方法を示しています。

/**
 * 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']
  ];
}

4 番目の例は、ストリーミング関数から動的スピル配列を返す方法を示しています。 結果は最初の例と同様にスピルダウンし、パラメーターに amount 基づいて 1 秒に 1 回インクリメントされます。 ストリーミング関数の詳細については、「ストリーミング 関数を作成する」を参照してください。

/**
 * 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);
  };
}

関連項目