google-apps-scriptgoogle-sheetsautoscroll

Trying to make a Google spreadsheet auto scroll to bottom filled in row. Tried a code but getting an error


I have the following code that I took from this question. I am trying to get my 400+ line Google sheet to auto-scroll to the bottom of the sheet on open instead of the first row. I am getting an error for the code on line 2.

TypeError: Cannot read property "source" from undefined. (line 2, file "Code")

I have a feeling it is because I have more than one tab on my spreadsheet, but I do not know code well enough to fix it. I would like it to only work on the first tab.

    function onOpen(e) {
      var spreadsheet = e.source;
      var sheet = spreadsheet.getActiveSheet();
      var lastRow = spreadsheet.getLastRow();
    /*  if (sheet.getMaxRows() == lastRow) {
        sheet.appendRow([""]);
      }
      lastRow = lastRow + 1;
      */
      var range = sheet.getRange("A" + lastRow + ":A" + lastRow);
      sheet.setActiveRange(range);
    }

Solution

  • The instructions that Vidar S. Ramdal gave in the referred topic and which @OlegValter has tried to explain in the comments are VERY important. Be sure to do them all.

    1. Go to Tools → Script editor and paste the following:

    function onOpen(){
     var ss = SpreadsheetApp.getActiveSpreadsheet();
     var sheetname = ss.getSheets()[0].getName();
     // Logger.log("DEBUG: sheetname = "+sheetname)
     var sheet = ss.getSheetByName(sheetname);
     var lastRow = sheet.getLastRow();
     var range = sheet.getRange(lastRow,1);
     sheet.setActiveRange(range);
    }
    

    1. Delete any existing code that is called onOpen(), onOpen(e) or similar.

    2. Click the Save button, then close the script editor, and the spreadsheet.

    3. Now, open your spreadsheet again. Give it a couple of seconds, and you should see the cursor drop to the Column A on last row of content on the first sheet. This will happen regardless of what sheet/row/column was active when you last used the spreadsheet.

    Note:

    onOpen() is not a function that can be run from the Script Editor as @OlegValter has explained. If you click "run" to execute the function, it will NOT work. It will ONLY execute when the spreadsheet is opened.


    Explanation