Google-sheets – How to copy range from last row to a new row created via script

google sheetsgoogle-apps-script

I saw the below code at How to automatically insert a new row and retain functions/formulas from last row?, and have a question on how to modify it so that instead of copying all content from the last row to the new one, I'd like to copy only a range of cells from the last row.

// global 
var ss = SpreadsheetApp.getActive();

function onOpen() {
  var menu = [{name:"Add New Last Row", functionName:"addRow"}];
  ss.addMenu("Extra", menu);
}

function addRow() {
  var sh = ss.getActiveSheet(), lRow = sh.getLastRow(); 
  var lCol = sh.getLastColumn(), range = sh.getRange(lRow,1,1,lCol);
  sh.insertRowsAfter(lRow, 1);
  range.copyTo(sh.getRange(lRow+1, 1, 1, lCol), {contentsOnly:false});
}

Best Answer

You could change range = sh.getRange(lRow,1,1,lCol) to fit your needs.

From https://developers.google.com/apps-script/reference/spreadsheet/sheet#getRange(Integer,Integer,Integer,Integer)

getRange(row, column, numRows, numColumns)

Returns the range with the top left cell at the given coordinates with the given number of rows and columns.

(follow the above link to see a code example)

Parameters

Name          Type          Description
row           Integer     the starting row of the range
column        Integer     the starting column of the range
numRows       Integer     the number of rows to return
numColumns    Integer     the number of columns to return