How do you copy a range and paste only rows with values into another sheet?

删除回忆录丶 提交于 2020-02-04 05:27:24

问题


Let me preface this by saying I realize the simple solution is to filter the column/uncheck blanks, copy, and paste values into the new column. The problem is that with teachers who aren't "tech savvy", nothing is simple.

With that said, I'm pulling data from multiple sheets in the same google spreadsheet into the "Master" sheet. I have a custom menu item called "Visibility" to hide/show the empty rows. After the rows are hidden, the teacher clicks the "Copy Data" button to copy A1:A to another sheet called "Copy". This is where I run into the problem - when the data is copied to the "Copy" sheet the empty rows are too. I just want the rows with values copied over.

Here's the script I'm using to copy the values from Master to Copy:

/**
 * A function named onEdit will be called whenever
 * a change is made to the spreadsheet.
 * 
 * @param  {object} e The edit event (not used in this case)
 */
function copyRange(e){
  var copyFromRange = 'Master!A1:A'; // no row for second cell reference
  var copyToRangeStart = 'Copy!A1';
  copyValuesOnly(copyFromRange, copyToRangeStart);
}

/**
 * This function will copy the values from a given range to
 * a second range, which starts from the given cell reference
 * 
 * @param  {string} copyFromRange    Range reference eg: 
 * @param  {string} copyToRangeStart Cell reference eg:
 */
function copyValuesOnly(copyFromRange, copyToRangeStart) {
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var source = ss.getRange(copyFromRange);
  source.copyTo(ss.getRange(copyToRangeStart), {contentsOnly: true});
}

Also, I edited a script I found to get what I'm working with so disregard the descriptions in my code. Thank you for any help you can provide!


回答1:


This should do it. Note: your link is not accessible.

function copyRangeNoEmpties(){
  var ss=SpreadsheetApp.getActive();
  var sh=ss.getSheetByName('Master');
  var copyToSheet=ss.getSheetByName('Copy');
  var copyFromRange=sh.getRange('A1:A');
  var vA=copyFromRange.getValues();
  var oA=[];
  for(var i=0;i<vA.length;i++)
  {
    if(vA[i][0])
    {
      oA.push([vA[i][0]]);
    }
  }
  var copyToRange=copyToSheet.getRange(1,1,oA.length,1);
  copyToRange.setValues(oA);
}


来源:https://stackoverflow.com/questions/45547313/how-do-you-copy-a-range-and-paste-only-rows-with-values-into-another-sheet

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