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

在参与公式值预览模式时,可以控制自定义函数计算结果的方式。 公式值预览模式是一项功能,允许最终用户在编辑单元格以预览值时选择公式的一部分。 此功能可帮助用户在编辑公式时评估公式。 下图显示了用户编辑公式并选择文本 A1+A2的示例。 公式预览模式显示上述值 7

Excel 公式编辑器的屏幕截图,其中选择了 A1+A2,并且公式编辑器上方显示的预览值为 7。

默认情况下,自定义函数 (例如 =getHousePrice(A1) ,用户可以预览) 。 但是,以下列表显示了你可能想要控制自定义函数参与公式值预览模式的方式的一些方案。

  • 自定义函数调用一个或多个 API,这些 API 按使用费率收费。
  • 自定义函数访问一个或多个稀缺资源,例如数据库。
  • 自定义函数需要花费大量时间来计算结果,并且它在预览期间对用户没有用处。

可以更改自定义函数的行为以改为返回模拟值。 为此, invocation.isInValuePreview 请使用只读属性。 下面的代码示例显示了一个名为 getHousePrice 的示例自定义函数,该函数通过盈利 API 查找房价。 如果 isInValuePreviewtrue,则自定义函数返回要使用的模拟数,并避免产生任何成本。 如果 isInValuePreviewfalse,则自定义函数调用 API 并返回在 Excel 电子表格中使用的实际房价值。

/**
 * 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 useable but fake number.
    return 450000; 
  } else { 
    // Make the actual service calls in this block. 
    const price = callHouseServiceAPI(address);
    return price; 
  } 
}

另请参阅