You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Google Apps Script:如何通过onChange触发器获取被删工作表名称?

解决Google Apps Script中获取被删除工作表名称的问题

原脚本里的e.getSheetName()确实无法获取被删除的工作表名称——因为onChange触发器触发时,目标工作表已经被移除,e对象返回的是当前活跃的工作表(也就是删除后自动跳转的那张)。要拿到被删的表名,核心思路是对比删除前后的工作表列表,找出缺失的项,具体实现如下:

关键修正点

  1. 原脚本中if (e.changeType = 'REMOVE_GRID')是赋值操作,会导致条件永远为真,必须改成严格相等判断===。
  2. 新增工作表名称的存储与对比逻辑,用PropertiesService(脚本属性存储)来记录删除前的所有表名,触发时对比找出被删项。

修改后的完整代码

// 初始化脚本属性,保存当前所有工作表名称(第一次运行一次即可)
function initSheetNames() {
  const ss = SpreadsheetApp.getActiveSpreadsheet();
  const sheetNames = ss.getSheets().map(sheet => sheet.getName());
  PropertiesService.getScriptProperties().setProperty('sheetNames', JSON.stringify(sheetNames));
}

// 创建onChange触发器(原逻辑保留,无需修改)
function removeMonthSheetFromList1(){
  ScriptApp.newTrigger('removeMonthSheetFromList2')
  .forSpreadsheet(SpreadsheetApp.getActive())
  .onChange()
  .create();
}

// 触发器触发后的逻辑处理
function removeMonthSheetFromList2(e){
  // 修正条件判断为严格相等
  if (e.changeType === 'REMOVE_GRID') {
    removeMonthSheetFromList(e);
  }
}

function removeMonthSheetFromList(e){
  const ss = SpreadsheetApp.getActiveSpreadsheet();
  const ssVariable = ss.getSheetByName('Feuille 15');
  const firstRow = 4;
  const column = 13;

  // 1. 获取存储的历史工作表名称列表
  const storedNamesStr = PropertiesService.getScriptProperties().getProperty('sheetNames');
  const storedNames = JSON.parse(storedNamesStr);
  // 2. 获取当前所有工作表名称列表
  const currentNames = ss.getSheets().map(sheet => sheet.getName());
  // 3. 对比找出被删除的工作表名称
  const deletedSheetName = storedNames.find(name => !currentNames.includes(name));

  if (deletedSheetName) {
    // 4. 查找匹配单元格并清除(原逻辑保留)
    const foundCell = ssVariable.getRange(firstRow, column, ssVariable.getLastRow() - firstRow + 1)
      .createTextFinder(deletedSheetName)
      .findNext();
    
    if (foundCell) {
      const cellToDelete = ssVariable.getRange(foundCell.getRow(), column);
      cellToDelete.clear();
    }

    // 5. 更新存储的工作表名称列表,为下次触发做准备
    PropertiesService.getScriptProperties().setProperty('sheetNames', JSON.stringify(currentNames));
  }
}

使用说明

  1. 先运行一次initSheetNames()函数,初始化存储当前的所有工作表名称。
  2. 后续每次删除工作表时,触发器会自动对比找出被删的表名,完成清除操作后更新存储的列表。

补充说明

  • 如果是多人协作的表格,建议改用PropertiesService.getDocumentProperties()(文档属性)替代getScriptProperties(),确保所有用户操作都基于同一套存储的表名。
  • 如果同时删除多个工作表,这段代码只会找出第一个缺失的表名;如果需要处理多表删除的场景,可以把find改成filter,遍历所有被删表名执行清除操作。

内容的提问来源于stack exchange,提问作者Magicrevette

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.25 16:02:44