I want to copy manually selected/highlighted non-adjacent rows and paste them directly below each other on another sheet ("fight list raw"). With the script below it works fine, as long as the rows are adjacent. If the rows are non-adjacent, only one row is pasted (the row which was selected lastly / where the cursor is in).
Has someone an idea how to manage it?
function copynonadjacent rows() {
SpreadsheetApp.flush();
var ss = SpreadsheetApp.getActiveSpreadsheet();
var target = SpreadsheetApp.getActiveSpreadsheet();
var source_sheet = ss.getActiveSheet();
var source_range = source_sheet.getActiveRange();
var target_sheet = target.getSheetByName("fight list raw");
var last_row = target_sheet.getLastRow();
target_sheet.insertRowsAfter(last_row,1);
source_range.copyTo(target_sheet.getRange("A" (last_row 1 ":AA" (last_row 1))),{contentsOnly:true});
}
Thanks a lot!
CodePudding user response:
From your following reply,
I want to copy row number 2 and row number 4. When I select the two rows by clicking on the row numbers and run the script, only row number 4 is copied.
But if I select rows 2 and 3 (so no rows between them), the script copies both rows. In the destination sheet the rows are pasted below each other without a row between them. I want this the same way, when I copy row 2 and 4.
In your script, you use var source_range = source_sheet.getActiveRange();
. I thought that this might be the reason for your issue. In this case, how about the following modification?
Modified script:
function myFunction() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
// Source sheet.
var source_sheet = ss.getActiveSheet();
var source_ranges = source_sheet.getActiveRangeList().getRanges();
var values = source_ranges.flatMap(r => r.getValues());
var len = values.length;
// Target sheet.
var target_sheet = ss.getSheetByName("fight list raw");
var last_row = target_sheet.getLastRow();
target_sheet.insertRowsAfter(last_row, len);
target_sheet.getRange(last_row 1, 1, len, values[0].length).setValues(values);
}
- When this script is run, the selected rows are retrieved, and copy the values to the target sheet.
- I thought that you use
{contentsOnly:true}
. So, I thought thatgetValues
andsetValues
might be able to be used.