I have a Google Sheets script that copies a range of cells from one tab to another. The problem is that I'd like it to only copy the non-blank range of cells, but instead it copies the entire range including blank rows. There are many versions of this problem already discussed, but I can't seem to find the right solution so I'm asking it again with all the specifics below.
The range I'm copying is comprised of:
- Column A contains a formula that has a text output if column B is
non-blank. If column B is blank, then the formula in column A
creates a blank entry (
""
). Columns B:J is an
=IMPORTRANGE
from a different sheet with the range set toA5:H
(open ended range).- Example Source data (imported into the main sheet)
- Example Main sheet (this contains the script, which can be triggered in the menu at the top under "Copy Data")
Here's the current script:
// custom menu function
function onOpen() {
var ui = SpreadsheetApp.getUi();
var menu = ui.createMenu('Copy Data');
var item = menu.addItem('Copy Data','copyData');
item.addToUi();
}
function copyData() {
// START1: get current sheet and tabs
var ss = SpreadsheetApp.getActiveSpreadsheet();
var current = ss.getSheetByName('ImportRange');
var database = ss.getSheetByName('RunningList');
// count rows to snap
var current_rows = current.getLastRow();
var database_rows = database.getLastRow() + 1;
var database_rows_new = current_rows + database_rows - 3;
var rows_new = current.getRange('A3:J' + current_rows).getValues();
var nonblank_values = rows_new.filter(String);
// snap rows, can run this on a trigger to be timed
database.getRange(database_rows, 1, nonblank_values.length, nonblank_values[0].length).setValues(nonblank_values);
}
Thank you for your time reviewing this problem.
EDIT 1
When I debug the script, it looks like the filter
function is not actually filtering out blank rows. So how would I actually do that?
Range
(i.e.getRange(database_rows, 1, nonblank.length, nonblank[0].length).setValues(nonblank);
) Further, have you tested thatString
is an appropriate predicate for 2D arrays like the ones obtained fromgetValues()
? – tehhowch// count rows to snap var range = current.getRange(database_rows, 1, nonblank.length, nonblank[0].length).setValues(nonblank);) var database_rows = database.getLastRow() + 1; var database_rows_new = getLastRow(range) + database_rows - 3;
The final section remains unchanged under the // snap rows heading. – pminc