如何通过脚本访问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); }
步骤拆解
- 先通过
getActiveSheet()和getActiveCell()拿到当前工作表与选中单元格 - 用
getRow()和getColumn()分别提取选中单元格的行、列数值,列数加1得到右侧单元格的列位置 - 调用
getRange(row, targetColumn)定位目标单元格,再用setValue()写入第二个提示框的输入内容
对应你的伪代码实现
你写的伪代码ActiveCell[row][column+1] = string input from prompt2,实际对应代码就是:sheet.getRange(activeCell.getRow(), activeCell.getColumn() + 1).setValue(input2)
内容的提问来源于stack exchange,提问作者hyped
相关产品推荐
相关产品推荐

