Home > OS >  Move multiple non adjacent rows on same sheet
Move multiple non adjacent rows on same sheet

Time:03-28

I am trying to move non-adjacent rows to specific rows on the same sheet but I can't get it to work. I have the following code so far:

    function moveRows() {
var sheet = SpreadsheetApp.getActiveSheet();
var rowSpec = sheet.getRangeList(["B11","B15"]);
sheet.moveRows("B2","B12")
}

This however returns the following error:

Exception: The parameters (String,String) don't match the method signature for SpreadsheetApp.Sheet.moveRows. moveRows @ Code.gs:4

From my searches, I haven't found a way to move multiple non-adjacent rows, so my first question is: Is it possible?

If not, is there a workaround and if so, how?

This is the sheet I am working on: https://docs.google.com/spreadsheets/d/1BKOxgZmAIoAzpmrF5NBChjFMXheyUEkf7SXVXCJs3zw/edit?usp=sharing

CodePudding user response:

Modification points:

  • In your script, var rowSpec = sheet.getRangeList(["B11","B15"]); is not used.
  • The arguments of moveRows(rowSpec, destinationIndex) are rowSpec (Range) and destinationIndex (Integer).
  • From I am trying to move non-adjacent rows to specific rows on the same sheet and your showing script, I thought that you might want to move from row 2 to row 12. If my understanding is correct, how about modifying it as follows?

Modified script:

function moveRows2() {
  var obj = [{"fromRow": 2, "toRow": 12}];
  var sheet = SpreadsheetApp.getActiveSheet();
  obj.forEach(({fromRow, toRow}) =>
    sheet.moveRows(sheet.getRange(`${fromRow}:${fromRow}`), toRow)
  );
}
  • When this script is run, row 2 is moved to row 11.

  • If you want to move other rows, please add it to obj like var obj = [{"fromRow": 2, "toRow": 12}, {"fromRow": 3, "toRow": 13},,,].

  • Or, from your script, if you want to move cell "B2" to cell "B12", how about the following modification?

      var obj = [{"fromCell": "B2", "toCell": "B12"}];
      var sheet = SpreadsheetApp.getActiveSheet();
      obj.forEach(({fromCell, toCell}) =>
        sheet.getRange(fromCell).moveTo(sheet.getRange(toCell))
      );
    
    • In this case, the cell after the cell value was moved becomes empty.

References:

  • Related