Skip to content

Instantly share code, notes, and snippets.

@nickburrows
Created April 19, 2023 03:40
Show Gist options
  • Save nickburrows/c0b86a8ff4f48df6c3d33bc8c6d0474b to your computer and use it in GitHub Desktop.
Save nickburrows/c0b86a8ff4f48df6c3d33bc8c6d0474b to your computer and use it in GitHub Desktop.
Google 試算表 - 用Google Apps Script新增自訂函式
  1. 開啟一個空白試算表檔案 (或現有的一個試算表檔案也可以)
  2. 點擊選單列「擴充功能 > Apps Script」
  3. 幫這份檔案取個名字
  4. 原始碼.gs 的檔案中貼上以下代碼
  5. 儲存檔案
  6. 回到試算表
  7. 在儲存格中輸入 =SPREADSHEETNAME()=SHEETNAME()=ALLSHEETNAMES()

SPREADSHEETNAME 顯示目前所使用的試算表名稱

/**
 * Returns the name of the Google Sheets spreadsheet.
 * 
 * @return The name of the Google Sheets spreadsheet.
 * @customfunction
 */
function SPREADSHEETNAME() {
  let ss = SpreadsheetApp.getActive();
  return ss.getName();
}

SHEETNAME 顯示目前所在的工作表名稱

/**
 * Returns the name of the active sheet.
 * 
 * @return The name of the active sheet.
 * @customfunction
 */
function SHEETNAME() {
  let activeSheet = SpreadsheetApp.getActiveSheet();
  return activeSheet.getName();
}

ALLSHEETNAMES 顯示目前試算表所有的工作表

/**
 * Returns the names of all sheets.
 * 
 * @return The name of all sheets in the Google Sheets spreadsheet.
 * @customfunction
 */
function ALLSHEETNAMES() {
  let ss = SpreadsheetApp.getActive();
  let sheets = ss.getSheets();
  let sheetNames = [];
  sheets.forEach(function (sheet) {
    sheetNames.push(sheet.getName());
  });
  return sheetNames;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment