Home > Blockchain >  Deleting multiple rows based on row date
Deleting multiple rows based on row date

Time:11-18

This enter image description here

Can someone help working out te solution?

  1. I thought of deleting a fixed amount on rows each day, but the number or rows may be different as there may be more calendar events.
  2. Previously, I had every row having a date. That doesn't look attractive.

CodePudding user response:

From what I understand, you want the script to delete all row entries that correspond to a date earlier than the current date (today). So assuming the sheet is ordered chronologically, it makes more sense for the loop to count the rows to be deleted from the top instead from the bottom.

That way you can use a single deleteRows() to remove a whole block at once.

Solution:

function deleteRow_nedeles_plani() 
{
    var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('Nedēļas plāni');
    var startRow = 3;  // First row of data to process
    var numRows = sheet.getLastRow()-2;   // Number of rows to process
    var dataRange = sheet.getRange(startRow, 1, numRows);
    // Fetch values for each row in the Range.
    var data = dataRange.getValues();

    for (i = 0; i < data.length; i  ) 
    {
          var row = data[i][0];
          var date = new Date();
          var sheetDate = new Date(row);
          var todayDate = Utilities.formatDate(date,'GMT 0300','yyyy-MM-dd')
          var rowDate = Utilities.formatDate(sheetDate,'GMT 0300', 'yyyy-MM-dd')
          Logger.log([rowDate.valueOf(), todayDate.valueOf()]);
          if (todayDate.valueOf() < rowDate.valueOf()) { break; }
    }

    sheet.deleteRows(3,i);
}

Sample Input:

enter image description here

After Execution:

enter image description here

  • Related