您可以使用 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,20)。第一个参数表示原价,第二个参数表示折扣百分比。 如果您所在的位置使用小数逗号,则可能需要改为输入=salePrice(100;20)。
您在单元格中输入的公式会在您在上一个部分中创建的脚本中运行该函数。该函数会得出 $80.00 的销售价格。
后续步骤
如需继续了解如何使用 Apps 脚本扩展 Google 表格,请参阅以下资源: