Scroll all worksheets to last row on open

只谈情不闲聊 提交于 2019-12-02 09:23:29

There isn't a good answer (that I could find) that addresses this topic in full:

The issue with your current script "ignoring" "all but the last iteration of the loop" stems from Google's own internal optimizations of the Spreadsheet Service:

Scripts commonly need to read in data from a spreadsheet, perform calculations, and then write out the results of the data to a spreadsheet. Google Apps Script already has some built-in optimization, such as using look-ahead caching to retrieve what a script is likely to get and write caching to save what is likely to be set.

In other words, your script is analyzed and effectively only the last activate call is determined to be needed. To counter this, we use SpreadsheetApp.flush() and Utilities.sleep, as done here.

function onOpen(e) { // "Simple Trigger" from reserved function name.
  // https://developers.google.com/apps-script/guides/triggers/events#open
  scrollAll(e.source);
}
function scrollAll(wb) {
  (wb ? wb : SpreadsheetApp.getActive()).getSheets().forEach(
    function (sheet) {
      wb.setActiveSheet(sheet).setActiveSelection("A" + sheet.getLastRow());
      SpreadsheetApp.flush();
      Utilities.sleep(1000); // may need to be adjusted
    });
}
function scrollActive() { // Macro target
  const s = SpreadsheetApp.getActiveSheet();
  s.setActiveSelection("A" + s.getLastRow());
}

To have a keyboard shortcut to re-scroll the current sheet to the bottom, you would include the following in your project's manifest file to bind the scrollActive function as a macro with a keyboard shortcut:

"sheets": {
  "macros": [{
    "menuName": "Scroll To Last Row",
    "functionName": "scrollActive",
    "defaultShortcut": "Ctrl+Alt+Shift+N" // N= 1, 2, 3, 4, 5, 6, 7, 8, 9, or 0
  }]
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!