自定义函数快速入门

您可以使用 Google Apps 脚本编写自定义函数,然后在 Google 表格就像一个内置函数。

以下快速入门示例将创建一个自定义函数,用于计算 折扣商品的促销价。促销价的格式为美元。

目标

  • 设置脚本。
  • 运行脚本。

前提条件

如需使用此示例,您需要满足以下前提条件:

  • Google 账号(Google Workspace 账号可能 需要管理员批准)。
  • 可以访问互联网的网络浏览器。

设置脚本

  1. 创建新的新 电子表格
  2. 在新电子表格中,选择菜单项 扩展程序 > Apps 脚本
  3. 删除脚本编辑器中的所有代码,并粘贴以下代码。然后 点击“保存”“保存”图标

    /**
     * Calculates the sale price of a value at a given discount.
     * The sale price is formatted as US dollars.
     *
     * @param {number} input The value to discount.
     * @param {number} discount The discount to apply, such as .5 or 50%.
     * @return The sale price formatted as USD.
     * @customfunction
     */
    function salePrice(input, discount) {
      let price = input - (input * discount);
      let dollarUS = Intl.NumberFormat("en-US", {
        style: "currency",
        currency: "USD",
    });
      return dollarUS.format(price);
    }
    

运行脚本

  1. 切换回电子表格。
  2. 在单元格中输入 =salePrice(100,.2)。第一个参数代表 第二个参数表示折扣百分比。 如果您所在位置使用小数逗号,您可能需要在 =salePrice(100;0,2)

您在单元格中输入的公式会在 您在上一部分中创建的脚本。此函数会生成销售 $80.00的价格。

后续步骤

要继续了解如何使用 Apps 脚本,请 请参阅以下资源: