2
votes

I'm writing a script for cleaning up spread sheets, These sheets are generated automatically and they contain a lot of irrelevant information. I need to scan for a heading, delete that row and then delete each additional row until coming to a row thats completely blank, just before the next heading group:

I can use the code below to scan for target text and delete the row. I can log each row I deleted: Logger.log("deleted rows: " + toDelete ); But I'm having trouble writing the rest

function deleteRows() {
  var sheet = SpreadsheetApp.getActiveSheet();
  var rows = sheet.getDataRange();
  var numRows = rows.getNumRows();
  var values = rows.getValues();

  var toDelete = [];
  var deleteExtra = [];

var re = new RegExp('(Member Service Associate|Contract Work)','gi'); 
  for (var row = 0; row < values.length; row++) { 
  for(var column = 0;column<values[row].length;column++){ 
  if (re.exec(values[row][column])){
  toDelete.push(row); } } }


  for(var deleteRow = toDelete.length-1; deleteRow >= 0;deleteRow--){
    sheet.deleteRow(toDelete[deleteRow]+1);
}    
Logger.log("deleted rows: " + toDelete );
SpreadsheetApp.flush();
};

Logger output:

[19-01-02 10:16:13:732 PST] deleted rows: 33,45,51,54,86,89,101,103,125,127,145,148,171,175,200,208,219,222,262,269,275,280,310,313,324,332,347,352,363,366,372,374,385,388

1
Okay maybe there are some similar parts here but its a little unclear how to proceedPerson Abide
Can you share a copy of your spreadsheet?Cooper

1 Answers

1
votes

Delete Unwanted and Adjacent Rows

Without having the benefit of being able to see your spreadsheets and you say that you want to keep deleting rows until you run into a blank row.

function deleteUnwantedAndAdjacentRows() {
  var sh=SpreadsheetApp.getActiveSheet();
  var rg=sh.getDataRange();
  var vA=rg.getValues();
  var d=0;//deleted count
  var kd=false;//keep deleting
  var re = new RegExp('(Member Service Associate|Contract Work)','gi'); 
  for (var i=0;i<vA.length;i++) { 
    if(vA[i].join("") && kd){//if something in this row and keep deleting is still true
      sh.deleteRow(i-d+1);//then delete
      d++;//increment delete count
      countinue;//go on to nextrow
    }else{//if row is blank
      kd=false;//quit deleting
    }
    for(var j=0;j<vA[i].length;j++){ 
      if(re.exec(vA[i][j])){
        sh.deleteRow(i-d+1);
        d++;
        kd=true;
      } 
    } 
  }    
}

Be sure to test this on something you can afford to mess up.