I've been trying to move the view of my spreadsheet when it's opened to the current date.
It's a scheduling spreadsheet with a sheet for each month, with dates listed in the first column going down.
I've successfully got the sheet to change to the current month with the following code:
function gotoCurrentMonth() {
var monthTabs = [ "January", "February", "March", "April", "May", "June",
"July", "August", "September", "October", "November", "December" ];
var month = (new Date()).getMonth();
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheetByName(monthTabs[month]);
sheet.activate();
}
This works with no problems when added to the onOpen function.
However the following code only works if it's triggered manually through the script editor, it doesn't seem to trigger when it's called after the gotoCurrentMonth function.
function gotoCurrentDay() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getActiveSheet();
//Get current day value from the MATCH spreadsheet function
//Example of cell value: 73
var range = sheet.getRange(2, 2).getValue();
//Go to bottom cell so that when it goes back up to current day, it's at the top of the screen
sheet.setActiveCell(sheet.getRange(sheet.getLastRow(), 1));
Logger.log("Select Last Row: " + sheet.getLastRow());
//Go back up to current day cell
sheet.setActiveCell(sheet.getRange(range, 1));
Logger.log("Select Current Day Row: " + range);
}
What happens is that the spreadsheet will switch to the March sheet when the spreadsheet opens, but the selected cell won't move. Sitting at the top of the March sheet.
If I then move my cursor back to January 1st (like it would normally when opened) and run the onOpen function manually after it's all loaded then it works fine and will select the current date properly.
My onOpen function:
function onOpen() {
gotoCurrentMonth();
gotoCurrentDay();
};
Any ideas as to why the onOpen function acts differently if it's activated manually or via the automated trigger?