Delete a row in Google Spreadsheets if value of cell in said row is 0 or blank

前端 未结 10 823
情书的邮戳
情书的邮戳 2020-11-29 02:01

I\'d like to be able to delete an entire row in a Google Spreadsheets if the value entered for say column \"C\" in that row is 0 or blank. Is there a simple script I could w

10条回答
  •  旧时难觅i
    2020-11-29 02:37

    The below code was able to delete rows containing a date more than 50 days before today in a particular column G , move these row values to back up sheet and delete the rows from source sheet.

    The code is better as it deletes the rows at one go rather than deleting one by one. Runs much faster.

    It does not copy back values like some solutions suggested (by pushing into an array and copying back to sheet). If I follow that logic, I am losing formulas contained in these cells.

    I run the function everyday in the night (scheduled) when no one is using the sheet.

    function delete_old(){
      //delete > 50 day old records and copy to backup
      //run daily from owner login
      var ss = SpreadsheetApp.getActiveSpreadsheet();  
      var bill = ss.getSheetByName("Allotted");
      var backss = SpreadsheetApp.openById("..."); //backup spreadsheet
      var bill2 = backss.getSheetByName("Allotted");
      var today=new Date();
      //process allotted sheet (bills)
      bill.getRange(1, 1, bill.getMaxRows(), bill.getMaxColumns()).activate();
      ss.getActiveRange().offset(1, 0, ss.getActiveRange().getNumRows() - 1).sort({column: 7, ascending: true});
      var data = bill.getDataRange().getValues();
      var delData = new Array();
      for(n=data.length-1; n>1; n--){
        if(data[n][6] !=="" &&  data[n][6]  < today.getTime()-(50*24*3600*1000) ){  //change the condition as per your situation
          delData.push(data[n]);
        }//if
       }//for
       //get first and last row no to be deleted
       for(n=1;n1; n--){
        if(data[n][6] !=="" &&  data[n][6]  < today.getTime()-(50*24*3600*1000) ){ 
          var ltrow=n+1 ; //last row
          break
        }//if
       }//for
       var bill2lr=bill2.getLastRow();
       bill2.getRange((bill2lr+1),1,delData.length,delData[0].length).setValues(delData);
       bill.deleteRows(strow, 1+ltrow-strow);
       bill.getRange(1, 1, bill.getMaxRows(), bill.getMaxColumns()).activate();
       ss.getActiveRange().offset(1, 0, ss.getActiveRange().getNumRows() - 1).sort({column: 6, ascending: true}); //get back ordinal sorting order as per column F
    }//function
    

提交回复
热议问题