Automatically delete empty rows with AppScript (Code Snipped)

I have Tables where data comes and goes, what creates many many empty rows after a while.
A script was needed to clean them periodically every day or so. Thankfully AppScript provides some free computing time we can use for that and we don't even need an AppScript subscription plan to make it run, because it can run completely on its own. So if you need something similar, here is my code you can start with.
Warning! If you don't know how to use it or don't even understand what it does, it is for sure not for you!

 

function cleanTables() {
  var doc = SpreadsheetApp.getActiveSpreadsheet();
  var sheets = [
    "add your table names here"
  ]
  var emptysFound = false;
  for(var s = 0; s < sheets.length; s++){
    var sheet = doc.getSheetByName(sheets[s]);
    var values = sheet.getRange(1, 1, sheet.getMaxRows(), sheet.getMaxColumns()).getValues();
    var cleaned = [];
    // run cleaning backwards because the sheet shrinks
    for(var r = values.length -1; r >= 1; r --){
      if(values[r].join("") == ""){
        cleaned.push(r+1);
        sheet.deleteRow(r + 1);
      }
    }
    if(cleaned.length > 0){
      emptysFound = true;
      console.log("Removed " + cleaned.length + " empty rows: (" + cleaned.reverse().join(",") + ") from table " + sheets[s] + ".");
    }
  }
  if(!emptysFound){
    console.log("No empty rows found, nothing to clean.")
  }
}

 

 

Solved Solved
2 1 174
1 ACCEPTED SOLUTION

Thank you  for a useful tip. If you post this tip in the "Tips and Tricks" section, it will have a better reach.

There have been some tips , questions and Apps Script based solutions on this topic before as below. However an alternate approach,  code as yours can always be useful. 

https://www.googlecloudcommunity.com/gc/Tips-Tricks/How-to-delete-blank-rows-in-Google-Sheets/m-p/38...

 

View solution in original post

1 REPLY 1
Top Labels in this Space