如何让我的谷歌电子表格打开今天的日期?

时间:2018-04-12 03:10:15

标签: google-apps-script google-sheets

以下是我的文档的链接: https://docs.google.com/spreadsheets/d/1wBpeCUTmePD3N5CDz57LeBBWZHnSwrX-5b6XscdbB4s/edit?usp=sharing

我希望该文件在今天的日期或每周的星期一开放。 请帮忙。 提前谢谢。

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;
    }
  }
} 

1 个答案:

答案 0 :(得分:0)

您尝试的主要问题是您抓取 A,但您的日期存在于中2.尝试此操作:

function onOpen() {
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var sheet = ss.getSheetByName("2018"); // Specifiy the sheet
  var range = sheet.getRange("2:2"); // Row 2
  var values = range.getValues()[0]; // This is a 2-dimensional array in the form [[row1-col1, row1-col2],[row2-col1,row2-col2]].
  // Because we only pulled one row (Row 2), we can immediately select just that row by appending the [0]

  var today = new Date();
  var todayDate = today.getDate();
  var todayMonth = today.getMonth();
  var todayYear = today.getFullYear();

  for (var i=0; i<values.length; i++) { 
    var columnDate = new Date(values[i]);
    if (columnDate.getDate() === todayDate && columnDate.getMonth() === todayMonth && columnDate.getFullYear() === todayYear) {
      sheet.getRange(1, i+1).activate();
      break;
    }
  }
}