Row count off by one in google spreadsheet

前端 未结 2 1591
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-12-22 03:42

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

相关标签:
2条回答
  • 2020-12-22 04:11

    You could do it in 'pure' array as well if you don't use formulas in your sheet.

    Like this for example :

    function deleteEmptyRows(){ 
     var sh = SpreadsheetApp.getActiveSheet();
     var data = sh.getDataRange().getValues();
     var targetData = new Array();
     for(n=0;n<data.length;++n){
     if(data[n].join().replace(/,/g,'')!=''){ targetData.push(data[n])};// checks the whole row
     Logger.log(data[n].join().replace(/,/g,''))
     }
     sh.getDataRange().clear(); // clear the whole sheet
     sh.getRange(1,1,targetData.length,targetData[0].length).setValues(targetData);//write back all non empty rows
     }
    
    0 讨论(0)
  • 2020-12-22 04:16

    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);
        }
      }
    }
    
    0 讨论(0)
提交回复
热议问题