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

后端 未结 2 667
醉梦人生
醉梦人生 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;
        }
      }
    }
    

提交回复
热议问题