您可以使用 Google Apps 脚本编写自定义函数,然后像使用内置函数一样在 Google 表格中使用它。
以下快速入门示例创建了一个自定义函数,用于计算打折商品的促销价。促销价采用美元格式。
目标
- 设置脚本。
- 运行脚本。
前提条件
如需使用此示例,您需要满足以下前提条件:
- Google 帐号(Google Workspace 帐号可能需要管理员批准)。
- 能够访问互联网的网络浏览器。
设置脚本
- 创建新的电子表格。
- 在新的电子表格中,依次选择扩展程序 > Apps 脚本菜单项。
删除脚本编辑器中的所有代码,然后将其粘贴到下面的代码中。然后点击“保存”图标
。
/** * 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 表格,请查看以下资源: