您可以使用 Google Apps Script 編寫自訂函式,然後像內建函式一樣在 Google 試算表中使用該函式。
以下快速入門導覽課程範例會建立自訂函式來計算折扣商品的特價。特價的格式為美元。
目標
- 設定指令碼。
- 執行指令碼。
必要條件
如要使用這個範例,您必須具備以下先決條件:
- 擁有 Google 帳戶 (Google Workspace 帳戶可能需要經過管理員核准)。
- 可以連上網際網路的網路瀏覽器。
設定指令碼
- 建立新試算表。
- 在新試算表中,依序選取「擴充功能」>「Apps Script」。
請刪除指令碼編輯器中的任何程式碼,然後貼上下方的程式碼。然後按一下「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 Script 擴充試算表,請參閱下列資源: