Help with simple Sheets Script

77 views
Skip to first unread message

john smith

unread,
May 6, 2024, 9:16:38 AMMay 6
to Google Apps Script Community
Morning y'all, to put things short I need help with a script for sheets. It's part of a mechanism that is supposed to skim through cells withing a range to check for stuff. I had it working, but for some reason selectNextCell() stopped working unexpectedly.  It's purpose is to just see what the current cell is, and then select the one to the right of it. Simple right? Well apparently not.

var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheets()[0];
var range = sheet.getRange('B2:X31');
range.activate();
var selection = SpreadsheetApp.getActiveSpreadsheet().getSelection();

function logger(){
  console.log(sheet.getCurrentCell().getA1Notation());
}

function selectNextCell() {
  var start = selection.getCurrentCell();
  var nextColumn = range.getCell(start.getRow(), start.getColumn()+1);
  nextColumn.activate();
}

function tester(){
  logger(); //B2
  selectNextCell();
  logger(); //C2
  selectNextCell();
  logger(); //C2
}

Again, this used to work but now it won't. It works once, but then it throws a pissy fit and doesn't want to do it more than once.

Any help would be greatly appreciated!

Edward Friedman (Eddie)

unread,
May 7, 2024, 10:09:27 PMMay 7
to Google Apps Script Community
I took your code and adjusted it to the following:

function logger() {
  console.log(SpreadsheetApp.getActiveSpreadsheet().getSheets()[0].getCurrentCell().getA1Notation());
}

function getSelectedCell() {
  return SpreadsheetApp.getActiveSpreadsheet().getSheets()[0].getSelection().getCurrentCell();
}

function selectNextCell() {
  return getSelectedCell().offset(0,1).activate();
}

function tester() {
  logger(); //B2
  selectNextCell();
  logger(); //C2
  selectNextCell();
  logger(); //C2
}

I put your global code into a function called getSelectedCell() which simply gets the selected cell on the first sheet in the spreadsheet. I adjusted selectNextCell() to use that function, and activate the cell to the right using the offset method.

Please note that if the next cell to the right is beyond the current columns in the sheet, the logger function will log that cell as the active one, but it won't appear on screen unless you write a value to that cell. For example, if you only have columns A thru B and run the tester function, it will log A1, B1, and C1, but column C will not appear on the screen unless you write a value to a cell in that column.

Hope this helps!

-Eddie Friedman

john smith

unread,
May 11, 2024, 2:12:45 PMMay 11
to Google Apps Script Community
Thank you so much! This worked great!
Reply all
Reply to author
Forward
0 new messages