简体   繁体   中英

Scroll through the spreadsheet to today's date using google app scripts

My google spreadsheet consists of columns:

  • A: Date
    1. 16.07.2020
    2. 17.07.2020
    3. 18.07.2020
  • B, C, D: Other information

I need a script that when you open the document will automatically scroll through the table to today's date.

Go to Today:

function gotoTodaysDate() {
  const ss=SpreadsheetApp.getActive();
  const sh=ss.getSheets()[0];//most left sheet
  const shsr=2;//data start row
  const shsc=1;//date column
  const vs=sh.getRange(shsr,shsc,sh.getLastRow()-shsr+1,1).getValues();
  const dates=vs.map(function(r){return r[0];});//flattened
  const td=Utilities.formatDate(new Date(), Session.getScriptTimeZone(), "dd.MM.yyyy");//current date string
  const idx=dates.indexOf(td);
  sh.getRange(idx+shsr,1).activate();
}

Installable onOpen Trigger:

function createOnOpenTrigger() {
  const ss=SpreadsheetApp.getActive();
  if(!isTrigger('gotoTodaysDate')) {
    ScriptApp.newTrigger('gotoTodaysDate').forSpreadsheet(ss.getId()).onOpen().create();
  }
}

Helper Function: Keeps you from creating more that one trigger for a given function

function isTrigger(funcName){
  var r=false;
  if(funcName){
    var allTriggers=ScriptApp.getProjectTriggers();
    for (let i=0;i<allTriggers.length;i++){
      if(funcName==allTriggers[i].getHandlerFunction()){
        r=true;
        break;
      }
    }
  }
  return r;
}

You may not need to have a script do that.

If your dates are in reverse order (ie, oldest up top to newest at the bottom), and you're just trying to get to the most recent date at the bottom, you can click in cell A1 and hit the Ctrl key along with the down-arrow key (ie, Ctrl-▼) on your keyboard, and you'll be taken there.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM