3
votes

The code needs to delete rows have a date before the current date. I'm not getting any syntax errors, but I think there is a semantic problem as the code will not change the spreadsheet in any way.

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
There is no height property of a sheet. Use the getLastRow() method. But, you'll still have a problem even if you change that. To delete rows, you need to iterate from the bottom up. Instead of an increment counter i++ you need to decrement i--.Alan Wells

1 Answers

4
votes

The code would probably look something like this:

function checkDateValue(e) {
  var colG_values,columnGCells,columnNumber,endDate,i,lastRow,
      sheet,startRow,todaysDate;
  
  startRow = 2;//Get data starting in this row
  columnNumber = 7://The column number to get the data from

  sheet = SpreadsheetApp.getActiveSpreadsheet().getSheets()[0];
  lastRow = sheet.getLastRow();
  
  todaysDate = new Date().getDate();
  //Logger.log('todaysDate: ' + todaysDate);

  columnGCells = sheet.getRange(startRow,columnNumber,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);//Delete this row
        }
      }
    }
  };
};

function runTest() {
  checkDateValue();
};