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

您可以使用 Google Apps Script 編寫自訂函式,然後在函式中使用 就像內建函式一樣

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

目標

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

必要條件

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

  • 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 請參閱下列資源: