CopyTo of filtered rows in GoogleSheets with Apps Script

Viewed 35

I am new in using Apps Script. I am trying to improve the workflow in my master document, but I am having some troubles.

In a Google Spreadsheet, I have a bunch of filtered data in Sheet "DATA". All the shown data should be copied to a another sheet right above the actual position of the cursor in this new sheet. In sheet "DATA" I am counting the number of visible rows which I use to define how many rows should be inserted and then copied. This is the script:

function myfunction() {
  var spreadsheet = SpreadsheetApp.getActive();
  var value = SpreadsheetApp.getActiveSheet().getRange('DATA!$B$1').getValue()
   spreadsheet.getActiveSheet().insertRowsBefore(spreadsheet.getActiveRange().getRow(), value);
   spreadsheet.getActiveRange().offset(0, 0, value, spreadsheet.getActiveRange().getNumColumns()).activate();
   spreadsheet.getRange('DATA!2:300').copyTo(spreadsheet.getActiveRange(), SpreadsheetApp.CopyPasteType.PASTE_NORMAL, false);
};

If the actual filter shows for example 3 rows, it inserts 3 empty rows perfectly fine, but then copies the values of 4 rows and therefore overwrites the data which I have in the 4th row. It seems to always copy the 1st row of the dataRange, although it is hidden by the filter.

If I include the first row in the filter, the copy works perfectly fine as it inserts 4 empty rows and the 4 copied rows.

Any idea what I am doing wrong?

0 Answers
Related