I want to delete empty rows. Row 885 is a non-empty row and should be retained. However, my code says (and shows in the msgbox) that 885 is empty and should be deleted. W
Below is some code which should accomplish what you want. You are correct in that the root of the problem is in the 0-based indexing. The tricky part is that JavaScript/Apps Script arrays use 0-based indexing, but when you call something like getLastRow()
, the returned range is 1-based. All-in-all, your code is good - it is only that issue that is tripping you up. Hope this helps:
function DeleteFun(){
var mySheet = SpreadsheetApp.getActiveSheet();
var range = mySheet.getDataRange();
// Iterate using a counter, starting at the last row and stopping at
// the header (assumes the header is in the first row)
for (i = mySheet.getLastRow() - 1; i > 0; i--) {
var foundAvalue = 0;
// Here we get the values for the current row and store in an array
rowRange = range.getValues()[i]
// Now we iterate through that array
for (j = 0; j <= rowRange.length; j++) {
// If any non-nulls are found, alert they won't be deleted and move on
if (rowRange[j] != null && rowRange[j] != '') {
foundAvalue = 1;
msg="Row " + (i+1) + " =" + rowRange[0] + " and will not be deleted";
Browser.msgBox(msg);
break;
}
}
if (foundAvalue == 0) {
msg="Row " + (i+1) + " =" + rowRange[0] + "WILL be deleted";
Browser.msgBox(msg);
// Delete empty row
mySheet.deleteRow(i+1);
}
}
}