Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Google Script Move selection to specific cell

I'm trying to move the cursor (select cell) when the user clicks on the Sheet. I've tried so many options and none of them work. The cursor just stays where I click, instead of moving to the specified cell. Note: I change the background color of the clicked cell just to make sure the selection trigger is working.

  function onSelectionChange(e) {
  
  var range = e.range;
  var sheet = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();

 
  range.setBackground("blue");

  sheet.setCurrentCell("a1").activate();
 
}

Any help greatly appreciated.

like image 688
Ken Allen Avatar asked Oct 31 '25 08:10

Ken Allen


1 Answers

The setCurrentCell method is never executed because you are using the wrong parameter for it.

According to the documentation here, setCurrentCell expects an object of type 'Range`, however, you are passing a string to it.

In order to fix this, you should update your function to this:

function onSelectionChange(e) {
  var range = e.range;
  var sheet = range.getSheet();
  range.setBackground("blue");
  var cell = sheet.getRange("A1");
  sheet.setCurrentCell(cell);
}

Also, since you are using the onSelectionChange trigger, for best practices, it is recommended you make use of the e event object, hence the modifications above.

Reference

  • Apps Script Spreadsheet Class - setCurrentCell(cell);

  • Apps Script Event Objects.

like image 92
ale13 Avatar answered Nov 03 '25 00:11

ale13