How to automatically delete rows that contain a date with more than 3 days offset to the past from now?

后端 未结 2 592
醉梦人生
醉梦人生 2021-01-06 15:07

I am trying to get a script going that will automatically delete rows with a date over 3 days old (4 days on)

I found this script that I was hoping to be able to adap

相关标签:
2条回答
  • 2021-01-06 15:28

    It will be much much faster if your rows are in order of date, newest at the top and you delete all the rows at once and not one at a time.

    function deleteOldData() {
      var ss = SpreadsheetApp.getActiveSpreadsheet();
      var sheet = ss.getSheetByName("CallHub1");
      var datarange = sheet.getDataRange();
      var lastrow = datarange.getLastRow();
      var values = datarange.getValues();// get all data in a 2D array
    
      var currentDate = new Date();
      var daysago = new Date().setDate(currentDate.getDate() - 3);
      var yearago = new Date().setDate(currentDate.getDate() - 365);
    
    
      for (i=lastrow;i>=2;i--) {
        var tempdate = values[i-1][0];// arrays are 0 indexed so row1 = values[0] and col3 = [2]
        if(tempdate < daysago)  {
          if(tempdate < yearago)  {continue;}
          sheet.deleteRows(1, i);
          break;
        }
      }
    }
    
    0 讨论(0)
  • 2021-01-06 15:30

    "date in column C, if that info is helpful"

    It is indeed ! instead of trying to get a date in column A as it it done in this line :

    var tempdate = sheet.getRange(i, 1).getValue();
    

    you should look at the value in column C like this :

    var tempdate = sheet.getRange(i, 3).getValue();
    

    but to be more efficient you should do these comparisons at array level, try it like below and it will run much faster ...

    var ss = SpreadsheetApp.getActiveSpreadsheet();
    var sheet = ss.getSheetByName("Foglio1");
    var datarange = sheet.getDataRange();
    var lastrow = datarange.getLastRow();
    var values = datarange.getValues();// get all data in a 2D array
    
    var currentDate = new Date();
    var oneweekago = new Date();
    oneweekago.setDate(currentDate.getDate() - 7);
    
    for (i=lastrow;i>=2;i--) {
    var tempdate = values[i-1][2];// arrays are 0 indexed so row1 = values[0] and col3 = [2]
    
    if(tempdate < oneweekago)  
    {
      sheet.deleteRow(i);
    }
    }
    }
    
    0 讨论(0)
提交回复
热议问题