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

Google Sheets脚本运行后需手动按ESC释放单元格,求自动解决方法

解决Google Apps Script运行后单元格需按ESC才能编辑的问题

你的问题出在脚本最后连续调用的activate()方法,导致单元格停留在编辑激活状态,必须手动按ESC退出。要实现自动释放单元格,只需调整脚本结尾逻辑,避免触发编辑模式即可。

修改后的完整脚本

function StockToInvoice() {
  var spreadsheet = SpreadsheetApp.getActive();

  // 定位到当前行的第一个单元格
  const currentCol = spreadsheet.getCurrentCell().getColumn();
  spreadsheet.getCurrentCell().offset(0, -(currentCol - 1)).activateAsCurrentCell();

  // 存储零件编号
  const stockcode = spreadsheet.getCurrentCell().getValue();

  // 切换到Shop工作表并写入零件编号
  const shopSheet = spreadsheet.setActiveSheet(spreadsheet.getSheetByName('Shop'), true);
  // 找到A20下方最后一个非空单元格,定位到下一个空行
  const lastDataCell = shopSheet.getRange('A20').getNextDataCell(SpreadsheetApp.Direction.DOWN);
  const targetRow = lastDataCell.getRow() + 1;
  
  // 写入零件编号到A列目标行
  shopSheet.getRange(targetRow, 1).setValue(stockcode);
  // 选中右侧B列单元格(仅选中,不进入编辑模式)
  shopSheet.setActiveRange(shopSheet.getRange(targetRow, 2));
}

关键修改点

  1. 移除了多次调用的activate(),改用setActiveRange()选中单元格——这个方法只会选中单元格,不会触发编辑模式。
  2. 用变量简化单元格定位逻辑,避免重复调用getCurrentCell()导致的状态混乱。
  3. 明确目标单元格定位方式,逻辑更清晰。

如果想保留原有操作逻辑,也可以在脚本末尾添加一行代码强制退出编辑状态:

// 在脚本最后添加
spreadsheet.getUi().executeMenuCommand('edit.cancel');

不过这种方式依赖Google Sheets的菜单命令,稳定性不如直接调整选中逻辑。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.17 01:10:27