Home > Net >  Editing this code to have one column overwrite another column
Editing this code to have one column overwrite another column

Time:01-30

I need to overwrite column C with the data in column F... But I want the headers in Row1 of each column to stay the same. This is the closest code that I have found as a starting point. It only moves shuffles two columns to the left. Whereas I am looking to overwrite one column with anoter while preserving the hearders

function moveColumns() {

  // get sheet
  var sheet = SpreadsheetApp.getActiveSheet();

  // select columns to be moved 
  var columnsToMove = sheet.getRange("E1:F1");

  // move columns to the left
  sheet.moveColumns(columnsToMove, 4);

}

the code above, I have been unable to alter

CodePudding user response:

Sheet.moveColumn() moves an entire column. You need to use Range.moveTo().

function moveColumns() {

  // get sheet
  var sheet = SpreadsheetApp.getActiveSheet();

  // get range of column F (6) starting with row 2
  var columnsToMove = sheet.getRange(2,6,sheet.getLastRow()-1,1);

  // move range to column C (3) starting at row 2
  columnsToMove.moveTo(sheet.getRange(2,3));

}

Reference

CodePudding user response:

Try this:

function moveColumns() {
  const ss = SpreadsheetApp.getActive();
  const sh = ss.getActiveSheet();
  const vs = sh.getRange("C2:F"   sh.getLastRow()).getValues();
  let o = vs.map(([c,d,e,f]) => [f]);
  sh.getRange(2,3, o.length,o[0].length).setValues(o);
}
  • Related