Note that it will only work if it is in the same function. Since the session still has the data where it was previously at. When the function stops, you don't have a way of knowing where was the previous selection was.
The sample code shows it merely returns to the previous activated cell of the sheet.
// Set the first sheet as the active sheet and select the range D4:F4.
spreadsheet.setActiveSheet(firstSheet).getRange('D4:F4').activate();
// Switch to the second sheet to do some work.
spreadsheet.setActiveSheet(secondSheet);
// Switch back to first sheet, and restore its selection.
spreadsheet.setActiveSheet(firstSheet, true);
What I can recommend you is create another sheet storing their previous active cells before the session ends.
Code:
var spreadsheet = SpreadsheetApp.getActiveSpreadsheet();
var sheet1 = spreadsheet.getSheetByName('Sheet1');
var sheet2 = spreadsheet.getSheetByName('Sheet2');
var record = spreadsheet.getSheetByName("record");
function changesheet() {
var sheet = spreadsheet.getActiveSheet();
var sheetName = sheet.getSheetName();
var selection = sheet.getActiveCell().getA1Notation();
if(sheetName == sheet1.getSheetName()){ // if in sheet1, go to sheet2
spreadsheet.setActiveSheet(sheet2);
var sheet2LastActiveCell = record.getRange("A2").getValue();
// if sheet2 was previously recorded, get it's last active cell
// else, go to A1 (default cell)
if(sheet2LastActiveCell)
sheet2.getRange(sheet2LastActiveCell).activateAsCurrentCell();
}
else if(sheetName == sheet2.getSheetName()){ // if in sheet2, go to sheet1
spreadsheet.setActiveSheet(sheet1);
var sheet1LastActiveCell = record.getRange("A1").getValue();
// if sheet1 was previously recorded, get it's last active cell
// else, go to A1 (default cell)
if(sheet1LastActiveCell)
sheet1.getRange(sheet1LastActiveCell).activateAsCurrentCell();
}
else // don't do anything if not in sheet1 or sheet2
return;
// record current cell of previous sheet
recordSheet(sheetName, selection);
}
function recordSheet(sheet, range){
if (sheet == sheet1.getSheetName())
// record sheet1 active cell in A1
record.getRange("A1").setValue(range)
else
// record sheet2 active cell in A2
record.getRange("A2").setValue(range)
}
Additional Notes:
- You can hide the record sheet after creating it.
- If not yet recorded, it will go to A1 by default.
getActiveCell
will always get the active cell of the active sheet. It can't get the active cell of non-active sheets.