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

如何通过脚本访问Google Sheets中选中单元格的右侧相邻单元格?

Google Sheets 脚本实现:将输入写入选中单元格右侧相邻单元格

核心操作方法

  • 获取选中单元格的行号:使用getRow()方法,示例:activeCell.getRow()
  • 获取选中单元格的列号:使用getColumn()方法,示例:activeCell.getColumn()
  • 定位右侧相邻单元格:通过getRange(row, column + 1)获取同行、列数+1的目标单元格

完整可运行代码

function writeToAdjacentCell() {
  // 获取当前活动工作表
  const sheet = SpreadsheetApp.getActiveSheet();
  // 获取当前选中的单元格
  const activeCell = sheet.getActiveCell();
  
  // 第一个提示框:写入原选中单元格
  const input1 = SpreadsheetApp.getUi().prompt('请输入要写入当前单元格的内容').getResponseText();
  activeCell.setValue(input1);
  
  // 第二个提示框:写入右侧相邻单元格
  const input2 = SpreadsheetApp.getUi().prompt('请输入要写入右侧单元格的内容').getResponseText();
  // 提取行号,计算右侧单元格列号
  const targetRow = activeCell.getRow();
  const targetColumn = activeCell.getColumn() + 1;
  // 定位目标单元格并写入内容
  const adjacentCell = sheet.getRange(targetRow, targetColumn);
  adjacentCell.setValue(input2);
}

步骤拆解

  1. 先通过getActiveSheet()和getActiveCell()拿到当前工作表与选中单元格
  2. 用getRow()和getColumn()分别提取选中单元格的行、列数值,列数加1得到右侧单元格的列位置
  3. 调用getRange(row, targetColumn)定位目标单元格,再用setValue()写入第二个提示框的输入内容

对应你的伪代码实现

你写的伪代码ActiveCell[row][column+1] = string input from prompt2,实际对应代码就是:
sheet.getRange(activeCell.getRow(), activeCell.getColumn() + 1).setValue(input2)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.18 22:01:16