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

您可以使用 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 擴充試算表,請參閱下列資源: