Google-sheets – How to open a specific tab based on today’s date (Google Sheets)

dategoogle sheetsgoogle-apps-scriptgoogle-apps-script-triggers

I've made a 'Google Sheets' with 31 tabs for the dates of the month (1-31)
How do I write a script that makes the spreadsheet open to that days tab?
e.g. open tab 25 if today is Aug 25th

I imagine (from a few other scripts I've seen) that it's something like:

function onOpen() {
  var date = getDate(now,'d')
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  ss.setActiveSheet(ss.getSheets()[date]);  
}

but I've never used this programming language and have no idea.

also, the tabs are named 1, 2, 3.. etc if that's any easier to code.

Best Answer

Assume that you have 31 sheets, named 1 to 31 respectively.

This script works when the spreadsheet is opened by using a simple onOpen trigger.

  • new Date(): gets today's date
  • now.getDate(); is a shorthand way of getting the day of the month. This is a number
  • ss.getSheetByName(sheetname);: assigns the day number to the sheet name
  • sheet.getRange("A1").activate();: goes to the specific sheet and to cell A1. The effect is to open the sheet equal to the day of the month.

function onOpen() {
  
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var now = new Date();
  var dayofmonth = now.getDate();
  var sheetname = dayofmonth;
  var sheet = ss.getSheetByName(sheetname);
  sheet.getRange("A1").activate();
  return;
  
}