Copying data after deleting empty rows in Google Sheets using Apps Script?

99封情书 提交于 2021-01-28 03:44:03

问题


The following code is working fine. It is sorting, removing duplicates and deleting empty rows. Then I just want to copy the rows of data to after the last data row. But the code is copying the rows of data with empty rows. Need to avoid empty rows while copying


var column = 3;   
range.sort({column: column, ascending:true});   
range.removeDuplicates([column]);   

//now delete empty rows if any   
for (var i = range.getHeight(); i >= 1; i--){
    if(range.getCell(i, 1).isBlank()){
            sheet.deleteRow(range.getCell(i, 1).getRow());
    }   
}
//For Double periods in a class    
var dataToCopy = range.getValues(); //Gets the values of the source range in a 2 dimensional array    
var copyData = sheet.getRange(range.getLastRow()+1,1,dataToCopy.length,dataToCopy[0].length).setValues(dataToCopy);

回答1:


I believe your goal as follows.

  • After the for loop in your script was finished, you want to retrieve the values without the empty rows.

For this, how about this answer?

Modification points:

  • In this answer, the number of delete rows is counted and the number is reduced from range of range.getValues();. By this, dataToCopy doesn't include the empty rows.

When above points are reflected to your script, it becomes as follows.

Modified script:

var column = 3;
range.sort({column: column, ascending:true});
range.removeDuplicates([column]);

//now delete empty rows if any

var deleteRows = 0;  // <--- Added

for (var i = range.getHeight(); i >= 1; i--){
    if(range.getCell(i, 1).isBlank()){
      sheet.deleteRow(range.getCell(i, 1).getRow());
      deleteRows++; // <--- Added
    }
}
//For Double periods in a class
var dataToCopy = range.offset(0, 0, range.getNumRows() - deleteRows).getValues();  // <--- Modified
var copyData = sheet.getRange(sheet.getLastRow()+1,1,dataToCopy.length,dataToCopy[0].length).setValues(dataToCopy); // <--- Modified
  • If you want to put the values to the last row of range, please modify the last line to the last line of your script.

References:

  • offset(rowOffset, columnOffset, numRows)
  • getLastRow() of Class Sheet


来源:https://stackoverflow.com/questions/62227320/copying-data-after-deleting-empty-rows-in-google-sheets-using-apps-script

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!