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

Google Script开发:单元格被设为空值时撤销修改恢复原值

解决方案

以下是修改后的脚本,可实现你需要的功能:

function onEdit(e) {
  const ss = e.source;
  const sheet = ss.getActiveSheet();
  const cell = e.range;
  const origValue = e.oldValue;
  const excludes = ['ALL','Offices'];
  
  // 跳过指定工作表
  if (excludes.includes(sheet.getName())) {
    return;
  }

  // 保留原有的列格式设置逻辑
  sheet.getRange("A5:A").setNumberFormat("m-d-yyyy");
  sheet.getRange("H5:H").setNumberFormat('h":"mm" "am/pm');
  sheet.getRange("J5:J").setNumberFormat('h":"mm" "am/pm');
  sheet.getRange("E5:E").setNumberFormat("0");
  sheet.getRange("L5:L").setNumberFormat("0");

  // 定义需要恢复旧值的列对应的列号(B=2, F=6, G=7, K=11, M=13)
  const targetColumns = [2, 6, 7, 11, 13];
  const currentColumn = cell.getColumn();

  // 仅当修改的单元格在目标列,且新值为空时,恢复为旧值
  if (targetColumns.includes(currentColumn) && e.value === "") {
    cell.setValue(origValue);
  }
}

关键修改说明

  • 触发器替换:将onSelectionChange改为onEdit,因为前者是选中单元格时触发,后者才是单元格值发生修改时触发,能准确捕获表单提交或手动编辑带来的数值变化。
  • 精准目标列判断:用列号数组明确指定需要处理的B、F、G、K、M列,避免误操作其他列。
  • 单个单元格操作:原代码会给整列赋值旧值,现在只修改触发事件的单个单元格,不会影响同列其他有效数据。
  • 条件逻辑优化:只有同时满足「目标列」和「新值为空」两个条件时,才执行恢复旧值的操作,逻辑更严谨。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.22 23:47:33