您可以使用 Google Apps 脚本编写自定义函数,然后在 Google 表格中像使用内置函数一样使用该函数。
以下快速入门示例创建了一个自定义函数,用于计算折扣商品的促销价。促销价的格式为美元。
目标
- 设置脚本。
- 运行脚本。
前提条件
如需使用此示例,您需要满足以下前提条件:
- Google 帐号(Google Workspace 帐号可能需要管理员批准)。
- 一个能够访问互联网的网络浏览器。
设置脚本
- 创建新电子表格。
- 在新电子表格中,依次选择菜单项扩展程序 > Apps 脚本。
删除脚本编辑器中的所有代码,然后粘贴以下代码。然后,点击“Save”
。
/** * 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); }
运行脚本
- 切换回电子表格。
- 在单元格中输入
=salePrice(100,.2)
。第一个参数表示原始价格,第二个参数表示折扣百分比。如果您所在的位置使用十进制英文逗号,则可能需要输入=salePrice(100;0,2)
。
您在单元格中输入的公式会运行您在上一部分中创建的脚本中的函数。该函数的促销价为 $80.00
。
后续步骤
如要继续学习如何使用 Apps 脚本扩展 Google 表格,请查看以下资源: