Programmatically delete empty rows

Viewed 1167

This is my sheet

As you can see row 2 and 6 are empty because I manually deleted some products. My question is how to programmatically delete those empty rows and be replaced with the other product-filled rows?

var ss = SpreadsheetApp.openById("my spreadsheet id");
var sheet = ss.getSheets()[0];
var data = sheet.getDataRange().getValues();
2 Answers

Delete All Empty Rows

function deleteEmpties() {
  //I would typically prefer SpreadsheetApp.getActive() but I used this because thats what you function contained
  const ss=SpreadsheetApp.openById("my spreadsheet id");
  //I would typical prefer using getSheetByName() but I used this because thats what your function contained
  const sh=ss.getSheets()[0];
  const shsr=2;//data start row
  const vs=sh.getRange(shsr,1,sh.getLastRow()-shsr+1,sh.getLastColumn()).getValues();
  let d=0;//delete counter
  vs.forEach(function(r,i){
    //deletes row if row is completely empty
    if(r.join('').length==0) {
      sh.deleteRow(i+shsr-d++)//increment delete counter on each delete because the rows are leaving the spreadsheet but not the data array
    }
  });
}
Related