Google电子表格选择列当前日期

时间:2014-04-18 09:43:45

标签: javascript google-sheets google-drive-api

我有一个电子表格,我们在其中制定计划。 从B列到最后一个可能的列,在A2行上有日期。 我试着编写一个将光标放在这个单元格上的函数。 但我有点卡住了,而且我对javascript的了解有限。

function onOpen() {
    getTodayRow();
};

function getTodayRow(){
    var ss = SpreadsheetApp.getActiveSpreadsheet();
    var sheet = ss.getSheetByName('2014a');
    var rowContent = sheet.getRange('B:A2').getValues();
    var today = new Date().getDate();
    var val = 1;
    for(var n in rowContent)
    {
        if (new Date(rowContent[n][0]).getDate() == today)
        {
            val=Number(n)+1;break
        }
    }
    SpreadsheetApp.getActiveSheet().getRange('A1').setValue(val);
    // return val;
    // the +1 above is because arrays count from 0 and rows count from 1. (Number() is to avoid having 13+1=131 which is the default behavior unfortunately)
    sheet.setActiveCell(sheet.getRange(2, val)); //activate on right date
}

有谁能告诉我哪里出错了?

2 个答案:

答案 0 :(得分:1)

我发现它并添加了一些调整,例如不需要输入工作表的名称。 你只需要制作你在第一行中使用的纸张。

function onOpen() {
  getTodayRow();
};

function getTodayRow(){
  var sheet = SpreadsheetApp.getActiveSheet();
  var rowContent = sheet.getRange(2, 2, 1, sheet.getLastColumn()).getValues()[0]; // [0] as we are using just one row i.e.
  var today = new Date();
  Logger.log(today);
  var val = 1;
  for(var n = 0; n < rowContent.length; n++) {
    var fDate = new Date(rowContent[n]);
    if (fDate.getDate() == today.getDate() && fDate.getMonth() == today.getMonth() && fDate.getFullYear() == today.getFullYear()) { // assuming its a number. If it's a formatted date you use if (new Date(rowContent[n] == today)
      val = n + 2 + 13; // + 2 because of arrays and the since the columns start from B => today
                        // + 2 + 13 to get today's date in the middle of the screen
      break;
    }
  }
  Logger.log(val);
  sheet.setActiveCell(sheet.getRange(2, val)); //activate on right date
}

thx for your help Konstant!

答案 1 :(得分:0)

以下是您可以使用的已编辑的getTodayRow函数。您可以根据自己的要求对其进行修改。

function getTodayRow(){
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var sheet = ss.getSheetByName('2014a');
  var rowContent = sheet.getRange(2, 2, 1, sheet.getLastColumn()).getValues()[0]; // [0] as we are using just one row i.e.
  var today = new Date().getDate();
  var val = 1;
  for(var n = 0; n < rowContent.length; n++) {
    if (rowContent[n] == today) { // assuming its a number. If it's a formatted date you use if (new Date(rowContent[n] == today)
      val = n + 2; // + 2 because of arrays and the since the columns start from B
      break;
    }
  }
  Logger.log(val);
  SpreadsheetApp.getActiveSheet().getRange('A1').setValue(val);
  // return val;
  sheet.setActiveCell(sheet.getRange(2, val)); //activate on right date
}