Home > Software design >  Copying and Pasting, but Pasting to Wrong Location
Copying and Pasting, but Pasting to Wrong Location

Time:07-13

I hope I post this correctly, first timer. Sorry in advance for any rules or formalities I violate.

Goal: I am trying to copy a range of data from a source tab, then paste the data into a target tab in the first available column in row 2, which is B2 (there is a header A1:Z1).

Issue: I want it to post the data in B2 as its the first open cell in row 2, but the code sees the first available column as AA as there is no header, so it posts the range starting in AA:2.

Help? Haha.


function movelog() {

var sheetFrom = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Entry");
var sheetTo = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Log");

// Copy from 3rd row, 5th column (E), all rows for one column 
var valuesToCopy = sheetFrom.getRange(3, 5, sheetFrom.getLastRow(), 1).getValues();

//Paste to another sheet from first cell onwards
sheetTo.getRange(2,sheetTo.getLastColumn() 1,valuesToCopy.length,1).setValues(valuesToCopy);

}

CodePudding user response:

Move Log

function movelog() {
  const ss = SpreadsheetApp.getActive();
  const sheetFrom = ss.getSheetByName("Entry");
  const sheetTo = ss.getSheetByName("Log");
  const valuesToCopy = sheetFrom.getRange(3, 5, sheetFrom.getLastRow() - 2).getValues();
  sheetTo.getRange(2, getRowWidth(2, sheetTo, ss)   1, valuesToCopy.length, 1).setValues(valuesToCopy);
}

function getRowWidth(row, sh, ss) {
  var ss = ss || SpreadsheetApp.getActive();
  var sh = sh || ss.getActiveSheet();
  var row = row || sh.getActiveCell().getRow();
  var rcA = [];
  if (sh.getLastColumn()) { rcA = sh.getRange(row, 1, 1, sh.getLastColumn()).getValues().flat().reverse(); }
  let s = 0;
  for (let i = 0; i < rcA.length; i  ) {
    if (rcA[i].toString().length == 0) {
      s  ;
    } else {
      break;
    }
  }
  return rcA.length - s;
}
  • Related