12

I would like that when I open any of my google spreadsheets the cursor be stepped on the last working cell (to remember the last position). Is this possible?

Thank you

4 Answers 4

12

You can create a trigger that runs every time your spreadsheet is opened.

This can probably be written more concisely but this would be the simplest idea, saving your row and cell properties upon each edit, and then setting them on open. Visit the Properties Service page to get some more info on which users can access those properties.

This will return to the last cell edited, not the last cell where the cursor had been.

ToolsScript editor and paste the following:

function onEdit(e) {

  var ss = e.source
  var sheet = ss.getActiveSheet();
  var cell = ss.getActiveCell();
  var row = cell.getRow();
  var column = cell.getColumn();
  var sheet_name = sheet.getSheetName();
  var scriptProperties = PropertiesService.getScriptProperties();  

  scriptProperties.setProperty('row',row);
  scriptProperties.setProperty('column',column);
  scriptProperties.setProperty('sheet name',sheet_name);
}

function onOpen(e) {

  var properties = PropertiesService.getScriptProperties();

  var ss = e.source;
  var sheet_name = properties.getProperty('sheet name');
  var sheet = ss.getSheetByName(sheet_name);
  var row = properties.getProperty('row');
  var column = properties.getProperty('column');
  var cell = sheet.getRange(row,column);

  ss.setActiveSheet(sheet);
  ss.setActiveRange(cell);  
}  
8
  • Thank you! and didn't marked as correct because it doesn't answer exactly the question, but is a really good approach and worked in one spreadsheet for me. I will try to make it work for all my spreadsheets, and then try to put the cursor in the last cell I was stepped.If I can't do that, or if anyone answer the question I will mark that as correct, if Mar 7, 2015 at 3:52
  • There's a class in Docs called Position to save the cursor position, but as far as I can see, nothing in Sheets. Unless there's a simple setting in Sheets I'm not seeing to save the state the user left off, I don't know if there's a way to get the cursor position. Good luck though.
    – Dan Oswalt
    Mar 7, 2015 at 5:38
  • thank you. I did not find the way to apply to all the documents (I mean, I didn't try really hard) what also because I think "maybe is not the best way, maybe I can screw all the documents") So I think I will try to find other way to work and avoid triggering an script before start. thank you for your answer, the script is very useful. Mar 18, 2015 at 2:18
  • @DanOswalt has this recently stopped working? It was such a useful macro and worked for years, but my sheet is suddenly putting me back to A1 on every startup.
    – WebMW
    Jul 7, 2021 at 20:53
  • glad is was useful for you! i haven't messed with google apps script in a long time. could be a change in api, or maybe just how you've logged in or something.
    – Dan Oswalt
    Jul 7, 2021 at 23:04
0

For those who want to remember last cursor position in Google Docs, here's one way to accomplish that.

// record current cursor position
function onCursorMove() {
  var doc = DocumentApp.getActiveDocument();
  var body = doc.getBody();
  var properties = PropertiesService.getScriptProperties();

  // temporary string for indicating cursor position
  var tempHinter = "3289asp"; // a random string
  DocumentApp.getActiveDocument().getCursor().insertText(tempHinter);
  var text = body.getText();
  var index = text.search(new RegExp(tempHinter, "g"));
  // delete temp string
  body.editAsText().deleteText(index, index + tempHinter.length - 1); // end offset is inclusive
  // store current cursor position as a script property
  properties.setProperty("position", index);
}

// set current cursor to last-stored position in script properties
function onOpen() {
  var properties = PropertiesService.getScriptProperties();
  var doc = DocumentApp.getActiveDocument();
  var body = doc.getBody();
  var text = body.editAsText();

  // get the cursor position stored by onCursorMove()
  var position = properties.getProperty("position");
  if (position !== null){
    // set cursor to last-stored position
    doc.setCursor(doc.newPosition(text, position));
  }
} 

Explanations:

  1. onCursoveMove(): record the current cursor's position in the document body's text and store the integer position in script properties for access after the document is closed and reopened. The DocumentApp.getActiveDocument().getCursor() function returns a Position object to represent the cursor's position. However, because Position uses element and offset to locate the cursor, it's very hard to store the element in script properties (JSON.stringify doesn't work for Element interface because it's too complex). To save the cursor location, I stored is an index in the document body's text.

  2. onOpen: Reset the current cursor to the last-stored position, using setCursor function

NOTE: As of Jan 2019, apps script doesn't have onClose() or onExit() trigger so onCursorMove() has to be periodically called to update the current cursor position. And since apps script doesn't support asynchronous processing, you may consider using HTMLService, TriggerBuilder, or other techniques to circumvent. Also the current execution time limit is 6 minutes.

1
  • Are you sure this can be used in Sheets?
    – vanowm
    Mar 19, 2022 at 18:57
0

Actual variant:

function onEdit(e) {

//  var ss = e.source;
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var sheet = ss.getActiveSheet();
  var cell = ss.getActiveCell();
  var row = cell.getRow();
  var column = cell.getColumn();
  var sheet_name = sheet.getSheetName();
//  var sheet_id = sheet.getSheetId();  
  var scriptProperties = PropertiesService.getScriptProperties();  

  scriptProperties.setProperty('row',row);
  scriptProperties.setProperty('column',column);
  scriptProperties.setProperty('sheet name',sheet_name);
//  scriptProperties.setProperty('sheet id',sheet_id);  
}
// set current cursor to last-stored position in script properties
function onOpen(e) {

  var properties = PropertiesService.getScriptProperties();

//  var ss = e.source;
  var ss = SpreadsheetApp.getActiveSpreadsheet();  
  var sheet_name = properties.getProperty('sheet name');
//  var sheet_id = properties.getProperty('sheet id');  
  var sheet = ss.getSheetByName(sheet_name);
  var row = Math.round( properties.getProperty('row'));
  var column = Math.round( properties.getProperty('column'));
  var cell = sheet.getRange(row,column);

  ss.setActiveSheet(sheet);
  ss.setActiveRange(cell);  
} 

0

The current version that works on all non-hidden sheets, and not just on the active one:

function onOpen() {
  const ss = SpreadsheetApp.getActiveSpreadsheet()
  const sheets = ss.getSheets()
  const properties = PropertiesService.getDocumentProperties()
  const lastActiveSheetName = properties.getProperty("lastActiveSheetName")
  let lastActiveSheet

  for (let sheet of sheets) {
    if (!sheet.isSheetHidden()) {
      const sheetName = sheet.getName()
      const lastEdit = properties.getProperty(sheetName)  
      if (lastEdit) {        
        if (sheetName !== lastActiveSheetName){
          sheet.getLastRow() // Without this magic does not work - I could not figure out the reasons
          sheet.getLastColumn() // Without this magic does not work - I could not figure out the reasons
          const [lastRow, lastCol] = lastEdit.split(',')
          sheet.getRange(Number(lastRow), Number(lastCol)).activate() // With focus set to this cell
          //sheet.setActiveSelection(sheet.getRange(Number(lastRow), Number(lastCol))) // Without setting focus to this cell
        }    
        else {
          lastActiveSheet = sheet
        }
      }
    }
  }

  if(lastActiveSheet){
    lastActiveSheet.getLastRow()
    lastActiveSheet.getLastColumn()
    const [lastRow, lastCol] = properties.getProperty(lastActiveSheetName).split(',')
    lastActiveSheet.getRange(Number(lastRow), Number(lastCol)).activate() 
  }
}

function onEdit() {
  const ss = SpreadsheetApp.getActiveSpreadsheet()
  const sheet = ss.getActiveSheet() 
  if (!sheet.isSheetHidden()) { 
    const cell = ss.getActiveCell()
    const row = cell.getRow()
    const column = cell.getColumn()
    if (row !== 1 || column !== 1) { // Protection from the evil magic of "self-editing" the first cell
      const sheetName = sheet.getName()
      PropertiesService.getDocumentProperties().setProperty(sheetName, `${row},${column}`)
      PropertiesService.getDocumentProperties().setProperty("lastActiveSheetName", sheetName) 
    }
  }
}

PS: Please note that in the code I do not use a semicolon separator - it's more convenient for me.

Not the answer you're looking for? Browse other questions tagged or ask your own question.