Home > Net >  Trying to select a certain spreadsheet cell after I complete an action in Google Apps script, but it
Trying to select a certain spreadsheet cell after I complete an action in Google Apps script, but it

Time:07-24

In my Google Sheets, I'm trying to select cell A1 after my onSelectionChange Google Apps script executes, but even though the rest of the script executes, the selection doesn't change at the end. Selecting cell A1 is supposed to be done by the last three lines of code below. These three lines of code work fine in another script for another sheet, but for some reason they won't work in this even simpler script.

function onSelectionChange(e) {  
// Insert date in a new cell, shifting existing cells down and then counting nonblank cells.
console.log("Start");
var range = e.range;
if(range.getColumn() >= 2
    && range.getColumn() <= 3
    && range.getNumRows() === 1
    && range.getRow() === 2)
  {     var d = new Date();
        range.offset(2,0).insertCells(SpreadsheetApp.Dimension.ROWS);
        range.offset(2,0).setValue(d);
        range.offset(1,0).setFormulaR1C1("counta(R[1]C[0]:C[0])");
        var sheet = range.getSheet();
        var cell = sheet.getRange("A1");
        sheet.setCurrentCell(cell);
  }
}

CodePudding user response:

Try Using activate() Instead

activate() sets the specified range in getRange("<Range>") as the active range. For your script, you simply need to modify the last line to select cell A1 after the process triggered is done. It should look like this:

function onSelectionChange(e) {  
// Insert date in a new cell, shifting existing cells down and then counting nonblank cells.
console.log("Start");
var range = e.range;
if(range.getColumn() >= 2
    && range.getColumn() <= 3
    && range.getNumRows() === 1
    && range.getRow() === 2)
  {     var d = new Date();
        range.offset(2,0).insertCells(SpreadsheetApp.Dimension.ROWS);
        range.offset(2,0).setValue(d);
        range.offset(1,0).setFormulaR1C1("counta(R[1]C[0]:C[0])");
        var sheet = range.getSheet();
        var cell = sheet.getRange("A1");
        cell.activate(); //change done in this line.
  }
}

Output

enter image description here

Reference

  • Related