計算分級定價折扣
透過集合功能整理內容
你可以依據偏好儲存及分類內容。
程式碼程度:初學者
時間長度:10 分鐘
專案類型:自訂函式
目標
- 瞭解解決方案的功能。
- 瞭解解決方案中的 Apps Script 服務功能。
- 設定指令碼。
- 執行指令碼。
認識這項解決方案
如果您為顧客提供分層定價系統,這個自訂函式可協助您輕鬆計算價格的折扣金額。
雖然您可以使用內建函式 SUMPRODUCT
進行分層價格計算,但與這個解決方案的自訂函式相比,使用 SUMPRODUCT
較為複雜且彈性較低。

運作方式
分層定價模式是指商品或服務的成本會根據購買數量而降低。
舉例來說,假設你有兩個等級,一個是 $0 美元至 $500 美元,可享 10% 折扣;另一個是 $501 美元至 $1,000 美元,可享 20% 折扣。假設要計算折扣的總價為 $700 美元,這時指令碼會將前 $500 美元乘以 10%,其餘 $200 美元乘以 20%,得出總折扣為 $90 美元。
針對特定總價,指令碼會逐一檢查層級價格表中的指定層級。總價中屬於各級別的部分,會乘以該級別的相關百分比值。最終結果是各層級計算結果的總和。
Apps Script 服務
這項解決方案會使用下列服務:
- 試算表服務:取得指定值,並計算要將該值的多少比例乘以各層級的折扣百分比。
必要條件
如要使用這個範例,您必須符合下列先決條件:
- Google 帳戶 (Google Workspace 帳戶可能需要管理員核准)。
- 可連上網際網路的網路瀏覽器。
設定指令碼
點選下方按鈕,複製「Tier pricing custom function」(分層定價自訂函式)試算表。這個解決方案的 Apps Script 專案會附加至試算表。
建立副本
執行指令碼
- 在複製的試算表中,第 16 列的表格會顯示軟體即服務 (SaaS) 產品的價格計算範例。
- 如要計算折扣金額,請在儲存格
C20
中輸入 =tierPrice(C19,$B$3:$D$6)
。最終價格會更新至儲存格 C21
。如果您所在地區使用小數點逗號,可能需要改為輸入 =tierPrice(C19;$B$3:$D$6)
。
檢查程式碼
如要查看這項解決方案的 Apps Script 程式碼,請按一下下方的「查看原始碼」:
修正規則
您可以視需要編輯自訂函式。以下是選用項目,可手動重新整理自訂函式結果。
重新整理快取結果
與內建函式不同,Google 會快取自訂函式,以提升效能。因此,如果您變更自訂函式中的某些項目 (例如正在計算的值),系統可能不會立即強制更新。如要手動重新整理函式結果,請按照下列步驟操作:
- 如要在空白儲存格中新增核取方塊,請依序點選「插入」>「核取方塊」。
- 將含有核取方塊的儲存格新增為自訂函式的額外參數。舉例來說,如果您在儲存格
D20
中新增核取方塊,請將儲存格 C20
中的 tierPrice()
函式更新為 =tierPrice(C19,$B$3:$D$6,D20)
。
- 勾選或取消勾選核取方塊,即可重新整理自訂函式結果。
貢獻者
這個範例由 Google 維護,並由 Google 開發人員專家協助。
後續步驟
除非另有註明,否則本頁面中的內容是採用創用 CC 姓名標示 4.0 授權,程式碼範例則為阿帕契 2.0 授權。詳情請參閱《Google Developers 網站政策》。Java 是 Oracle 和/或其關聯企業的註冊商標。
上次更新時間:2025-08-31 (世界標準時間)。
[null,null,["上次更新時間:2025-08-31 (世界標準時間)。"],[[["\u003cp\u003eThis Google Apps Script custom function simplifies tiered pricing calculations in Google Sheets, offering a more straightforward approach than using \u003ccode\u003eSUMPRODUCT\u003c/code\u003e.\u003c/p\u003e\n"],["\u003cp\u003eThe function calculates discounts by iterating through pricing tiers, applying the corresponding percentage discount to the portion of the total price falling within each tier.\u003c/p\u003e\n"],["\u003cp\u003eTo use the function, you need to provide the total price and a table specifying the pricing tiers, start and end values, and discount percentages.\u003c/p\u003e\n"],["\u003cp\u003eThe script utilizes the Spreadsheet service to access and process data within the sheet.\u003c/p\u003e\n"],["\u003cp\u003eYou can manually refresh the custom function's results by adding a checkbox and including its cell reference as an additional parameter in the function call.\u003c/p\u003e\n"]]],[],null,["# Calculate a tiered pricing discount\n\n**Coding level** : Beginner \n\n**Duration** : 10 minutes \n\n**Project type** : [Custom function](/apps-script/guides/sheets/functions)\n\nObjectives\n----------\n\n- Understand what the solution does.\n- Understand what the Apps Script services do within the solution.\n- Set up the script.\n- Run the script.\n\nAbout this solution\n-------------------\n\nIf you offer a tiered pricing system for your customers, this custom function\nmakes it easier to calculate the discount amounts for your prices.\n\nThough you could use the built-in function `SUMPRODUCT` to make a tiered pricing\ncalculation, using `SUMPRODUCT` is more complex and less flexible than this\nsolution's custom function.\n\n### How it works\n\nA tiered pricing model means that the cost of goods or services goes down\nbased on the quantity purchased.\n\nFor example, imagine you have two tiers, one that ranges from $0-$500 and is\ndiscounted by 10% and one that ranges from $501-$1,000 and is discounted by 20%.\nIf the total price you need to calculate a discount for is $700, the script\nmultiplies\nthe first $500 by 10% and the remaining $200 by 20%, for a total discount of\n$90.\n\nFor a given total price, the script loops through the specified tiers in the\ntier pricing table. For each portion of the total price that falls\nwithin a tier, that portion is multiplied by the tier's associated percent\nvalue. The result is the sum of each tier's calculation.\n\n### Apps Script services\n\nThis solution uses the following service:\n\n- [Spreadsheet service](/apps-script/reference/spreadsheet)--Takes the given value and calculates what portion of the value to multiply by each tier's percent discount.\n\nPrerequisites\n-------------\n\nTo use this sample, you need the following prerequisites:\n\n- A Google Account (Google Workspace accounts might require administrator approval).\n- A web browser with access to the internet.\n\nSet up the script\n-----------------\n\nClick the button below to make a copy of the **Tier pricing custom function**\nspreadsheet. The Apps Script project for\nthis solution is attached to the spreadsheet.\n\n[Make a copy](https://docs.google.com/spreadsheets/d/13X-3pz8P_sfAyNqUJrGe0HdgzKARIMxC6Y6xZDAF7M0/copy)\n\nRun the script\n--------------\n\n1. In your copied spreadsheet, the table at row 16 shows a sample price calculation for a Software as a Service (SaaS) product.\n2. To calculate the discount amount, in cell `C20`, enter `=tierPrice(C19,$B$3:$D$6)`. The final price updates in cell `C21`. If you're in a location that uses decimal commas, you might need to enter `=tierPrice(C19;$B$3:$D$6)` instead.\n\nReview the code\n---------------\n\nTo review the Apps Script code for this solution, click **View source code**\nbelow: \n\n#### View source code\n\n### Code.gs\n\n\u003cbr /\u003e\n\nsolutions/custom-functions/tier-pricing/Code.js \n[View on GitHub](https://github.com/googleworkspace/apps-script-samples/blob/main/solutions/custom-functions/tier-pricing/Code.js) \n\n```javascript\n// To learn how to use this script, refer to the documentation:\n// https://developers.google.com/apps-script/samples/custom-functions/tier-pricing\n\n/*\nCopyright 2022 Google LLC\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n https://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\n/**\n * Calculates the tiered pricing discount. \n * \n * You must provide a value to calculate its discount. The value can be a string or a reference\n * to a cell that contains a string.\n * You must provide a data table range, for example, $B$4:$D$7, that includes the \n * tier start, end, and percent columns. If your table has headers, don't include\n * the headers in the range.\n * \n * @param {string} value The value to calculate the discount for, which can be a string or a \n * reference to a cell that contains a string.\n * @param {string} table The tier table data range using A1 notation.\n * @return number The total discount amount for the value.\n * @customfunction\n * \n */\nfunction tierPrice(value, table) {\n let total = 0;\n // Creates an array for each row of the table and loops through each array.\n for (let [start, end, percent] of table) {\n // Checks if the value is less than the starting value of the tier. If it is less, the loop stops.\n if (value \u003c start) {\n break;\n }\n // Calculates the portion of the value to be multiplied by the tier's percent value.\n let amount = Math.min(value, end) - start;\n // Multiplies the amount by the tier's percent value and adds the product to the total.\n total += amount * percent;\n }\n return total;\n}\n```\n\n\u003cbr /\u003e\n\n\u003cbr /\u003e\n\nModifications\n-------------\n\nYou can edit the custom function as much as you'd like to fit your needs. Below\nis an optional addition to manually refresh custom function results. \n\n#### Refresh cached results\n\n\nUnlike built-in functions, Google caches custom functions to optimize\nperformance. Therefore, if you change something within your custom\nfunction, such as a value that's being calculated, it might not immediately\nforce an update. To refresh the function result manually, take the following\nsteps:\n\n1. Add a checkbox to an empty cell by clicking **Insert** \\\u003e **Checkbox**.\n2. Add the cell that has the checkbox as an extra parameter of the custom function. For example, if you add a checkbox to cell `D20`, update the `tierPrice()` function in cell `C20` to `=tierPrice(C19,$B$3:$D$6,D20)`.\n3. Check or uncheck the checkbox to refresh the custom function results.\n\nContributors\n------------\n\nThis sample is maintained by Google with the help of Google Developer Experts.\n\nNext steps\n----------\n\n- [Custom functions in Google Sheets](/apps-script/guides/sheets/functions)\n- [Extending Google Sheets](/apps-script/guides/sheets)"]]