在自定义函数中使用公式值预览模式

公式值预览模式可帮助用户在编辑公式时评估公式。 当用户选择公式的一部分时,Excel 将计算并显示所选值。 例如,下图显示了所选表达式 A1+A2的7预览值。

Excel 公式编辑器的屏幕截图,其中选择了 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;
  }
}

另请参阅