Using onEdit trigger, is there a way to make sure the last row in a Sheet is visible to users?

橙三吉。 提交于 2021-02-05 09:25:09

问题


I have a Google Sheet that accumulates up to 100 entries per day. As users add new entries, the script puts new data into the last row (see snippet below). However, there are only 12 rows visible on the screen, so once those are filled, the user can't see new entries.

How can I make the last row visible to the user each time data is entered?

I am new to google-apps-script, so thanks for any ideas. I believe onEdit trigger no longer works with sheet.setActiveRange(), so I am looking for a work-around. If there's no simple solution, I'll take a clunky one. For example, can a script be used to hide rows above the last row?

    var ss = SpreadsheetApp.getActiveSpreadsheet();
    var SHEET_NAME = 'Sheet1' // Name of current sheet
    var sheet = ss.getSheetByName(SHEET_NAME);
    var dataCell = sheet.getRange('A1');
    var lastRowNumber = sheet.getDataRange().getNumRows();
    var newData = dataCell.getValue().split(",");
    var lastRow = ss.getLastRow();

    sheet.appendRow(newData);

回答1:


You could get the newly added range by adding 1 to the lastrow and activate it:

var lastRow = ss.getLastRow();
sheet.appendRow(newData);
sheet.getRange("A" + (lastRow+1)).activate();//activate the newly appended row's A cell



回答2:


Found a solution: setActiveRange(lastRow+2, lastColumn). Scrolls down far enough, without the need to get the range of the appended row. Added advantage is it scrolls before the row is appended, so user sees data as it goes in.

function onEdit(e) { // Puts csv user data into Sheet1
    var ss = SpreadsheetApp.getActiveSpreadsheet();
    var SHEET_NAME = 'Sheet1' // Name of current sheet
    var sheet = ss.getSheets()[0];
    var dataCell = sheet.getRange('A1');
    var newData = dataCell.getValue().split(",");

     // Gets the address of the very last cell of this sheet
     var lastRow = sheet.getLastRow();
     var lastColumn = sheet.getLastColumn();

     // Scrolls to make sure user can see 2 rows below the current last cell
     var lastCell = sheet.getRange(lastRow+2, lastColumn);

    // Puts user entered data into a new row at the bottom of the spreadsheet
    sheet.appendRow(newData);
    sheet.setActiveRange(lastCell);
}


来源:https://stackoverflow.com/questions/58041802/using-onedit-trigger-is-there-a-way-to-make-sure-the-last-row-in-a-sheet-is-vis

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!