I am trying to make it so when anyone who is in this weekly calendar opens the doc, it locks to the week we are currently in.
Our dates are in row 4, going across the top of the doc and run from June through December. I need the calendar to open to the week we are currently in when it is opened.
I've seen scripts for locking to today's date, but because we only have the Monday of each week listed, these do not work. Can it lock to a certain cell?
This is the code I tried already:
function onOpen() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getActiveSheet();
var range = sheet.getRange("A:A");
var values = range.getValues();
var day = 24*3600*1000;
var today = parseInt((new Date().setHours(0,0,0,0))/day);
var ssdate;
for (var i=0; i<values.length; i++) {
try {
ssdate = values[i][0].getTime()/day;
}
catch(e) {
}
if (ssdate && Math.floor(ssdate) == today) {
sheet.setActiveRange(range.offset(i,0,1,1));
break;
}
}
}
Best Answer
This answer can be adapted to the layout used by the OP, as well as to a trigger.
There are usually many ways that a given problem can be solved; this should be considered as just one alternative.
Aspects to note:
getDay()
to return the day of the week.This is the equivalent of the
WEEKDAY
function in Google Sheets except that the Javascript method is zero-based. Then calculated the number of days (nowadj
) that needs to be adjusted to get to the previous Monday.getRange
andgetValues
to get the date range; but then converted the data to a 1D array; then converted those values to strings.used a small sub-routine described by Serge inasas to subtract a given number of days from today's date. This returns the date for last Monday.
used indexOf to find last Monday's date in the list of calendar dates. The result gives the column number, but note that this is zero-based (so add 1) and the data range started at Column B (so add 1 to allow for Column A).
used code described by Serge insas in "UPDATE: When sheet is opened, would like to auto-jump to certain cell based on date" as best alternative to scroll to the cell.
Calendar layout used in this answer