自訂函式快速入門導覽課程

您可以使用 Google Apps Script 撰寫自訂函式,然後在 Google 試算表中像內建函式一樣使用。

下列快速入門範例會建立自訂函式,計算折扣商品的特價。特價價格的格式為美元。

目標

  • 設定指令碼。
  • 執行指令碼。

必要條件

如要使用這個範例,您必須符合下列先決條件:

  • Google 帳戶 (Google Workspace 帳戶可能需要管理員核准)。
  • 可連上網際網路的網路瀏覽器。

設定指令碼

  1. 建立新試算表
  2. 在新試算表中,依序選取選單項目「擴充功能」>「Apps Script」
  3. 刪除指令碼編輯器中的任何程式碼,然後貼上以下程式碼。然後按一下「儲存」圖示 「儲存」圖示

    /**
     * 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);
    }

執行指令碼

  1. 切換回試算表。
  2. 在儲存格中輸入 =salePrice(100,.2)。第一個參數代表原價,第二個參數代表折扣百分比。如果您所在地區使用小數點逗號,可能需要改為輸入 =salePrice(100;0,2)

您在儲存格中輸入的公式會執行您在上一節建立的指令碼中的函式。函式會產生 $80.00 的特價。

後續步驟

如要繼續瞭解如何使用 Apps Script 擴充 Google 試算表功能,請參閱下列資源: