自定义函数快速入门
使用集合让一切井井有条
根据您的偏好保存内容并对其进行分类。
您可以使用 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 脚本,请
请参阅以下资源:
如未另行说明,那么本页面中的内容已根据知识共享署名 4.0 许可获得了许可,并且代码示例已根据 Apache 2.0 许可获得了许可。有关详情,请参阅 Google 开发者网站政策。Java 是 Oracle 和/或其关联公司的注册商标。
最后更新时间 (UTC):2024-09-10。
[{
"type": "thumb-down",
"id": "missingTheInformationINeed",
"label":"没有我需要的信息"
},{
"type": "thumb-down",
"id": "tooComplicatedTooManySteps",
"label":"太复杂/步骤太多"
},{
"type": "thumb-down",
"id": "outOfDate",
"label":"内容需要更新"
},{
"type": "thumb-down",
"id": "translationIssue",
"label":"翻译问题"
},{
"type": "thumb-down",
"id": "samplesCodeIssue",
"label":"示例/代码问题"
},{
"type": "thumb-down",
"id": "otherDown",
"label":"其他"
}]
[{
"type": "thumb-up",
"id": "easyToUnderstand",
"label":"易于理解"
},{
"type": "thumb-up",
"id": "solvedMyProblem",
"label":"解决了我的问题"
},{
"type": "thumb-up",
"id": "otherUp",
"label":"其他"
}]
{"lastModified": "\u6700\u540e\u66f4\u65b0\u65f6\u95f4 (UTC)\uff1a2024-09-10\u3002"}
[[["易于理解","easyToUnderstand","thumb-up"],["解决了我的问题","solvedMyProblem","thumb-up"],["其他","otherUp","thumb-up"]],[["没有我需要的信息","missingTheInformationINeed","thumb-down"],["太复杂/步骤太多","tooComplicatedTooManySteps","thumb-down"],["内容需要更新","outOfDate","thumb-down"],["翻译问题","translationIssue","thumb-down"],["示例/代码问题","samplesCodeIssue","thumb-down"],["其他","otherDown","thumb-down"]],["最后更新时间 (UTC):2024-09-10。"]]