循环通过谷歌表删除行

时间:2016-06-10 17:31:22

标签: google-apps-script google-sheets

我正在尝试编写一些代码,允许我遍历电子表格并替换当前日期之前的日期。理想情况下,在日期列中的日期超过当前日期的任何行都将从表中删除。我没有得到任何语法错误,但我认为存在语义问题,因为代码不会以任何方式更改电子表格。我不确定到底需要做些什么才能解决这个问题。

function checkDateValue(e) {
    var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheets()[0];
    var todaysDate = new Date().getDate();
    var columnGCells = sheet.getRange("G2:G");
    var columnG = columnGCells.getValues();

    for (i = 1; i < sheet.height; i++) {
        var endDate = new Date()
        endDate = columnG[i];
        if (todaysDate.getYear() >= endDate.getYear()){
          if (todaysDate.getMonth() >= endDate.getMonth()){
            if (todaysDate.getDay >= endDate.getDay()){
              sheet.deleteRow(i);
            }
          }
        }
      }
};
checkDateValue();

1 个答案:

答案 0 :(得分:2)

代码可能看起来像这样:

function checkDateValue(e) {
  var colG_values,columnGCells,endDate,i,lastRow,sheet,todaysDate;

  sheet = SpreadsheetApp.getActiveSpreadsheet().getSheets()[0];
  lastRow = sheet.getLastRow();

  todaysDate = new Date().getDate();
  Logger.log('todaysDate: ' + todaysDate);

  columnGCells = sheet.getRange(2,7,lastRow-1,1);
  colG_values = columnGCells.getValues();

  for (i = lastRow; i > 1; i--) {//Loop through values from last to first. Need to stop at row one.
    endDate = colG_values[i];
    endDate = new Date(endDate);

    if (todaysDate.getYear() >= endDate.getYear()){
      if (todaysDate.getMonth() >= endDate.getMonth()){
         if (todaysDate.getDay >= endDate.getDay()){
           sheet.deleteRow(i);
        }
      }
    }
  };
};
checkDateValue();