カスタム関数で数式値プレビュー モードを操作する

数式値プレビュー モードは、ユーザーが数式を編集するときに評価するのに役立ちます。 ユーザーが数式の一部を選択すると、選択した値が計算されて表示されます。 たとえば、次の図は、選択した式A1+A27のプレビュー値を示しています。

A1 + A2 が選択され、数式エディターの上にプレビュー値 7 が表示されている Excel 数式エディターのスクリーンショット。

既定では、数式値のプレビュー中にカスタム関数が実行されます。 この動作は、カスタム関数の動作に応じて問題が発生する可能性があります。 読み取り専用の invocation.isInValuePreview プロパティを使用してプレビュー計算を検出し、完全な計算で次の場合にモック値を返します。

  • 従量制課金 API を呼び出します。
  • データベースなどの制限付きリソースにアクセスします。
  • 便利なプレビューを提供するには時間がかかりすぎます。

次の getHousePrice カスタム関数は、プレビュー中にモック価格を返します。 標準計算では、従量制課金サービスを呼び出し、実際の価格を返します。

/**
 * Get the listing price for a house on the market for the given address.
 * @customfunction
 * @param address The address of the house.
 * @param invocation Custom function handler.
 * @returns The price of the house at the address.
 */
export function getHousePrice(address: string, invocation: CustomFunctions.Invocation): number {
  // Check if this call is for formula value preview mode.
  if (invocation.isInValuePreview) {
    // Avoid long-running expensive service calls.
    // Return a usable but fake number.
    return 450000;
  } else {
    // Make the actual service calls in this block.
    const price = callHouseServiceAPI(address);
    return price;
  }
}

関連項目