Home > Software engineering >  Duplicating Google Sheets tab and transferring a column of data from original to new duplicated tab
Duplicating Google Sheets tab and transferring a column of data from original to new duplicated tab

Time:01-04

I have a Google Sheets document that I use on a weekly basis in the following manner:

  • Duplicate existing tab.
  • Rename duplicated tab based on a cell value incremented by 7 days.
  • Take "Budget" column from original tab and paste to "Last Week's Budget" column in duplicated tab. Attached is an example screenshot. Current Google Sheets Format

I am at a loss on how to incorporate the copy/paste portion where I am trying to move the "Budget" from original tab to "Last Week's Budget" in the new/duplicated tab.

I have figured out to duplicate the existing tab and rename it as needed, and the script I have is below based on another Stack Overflow question:

var localTimeZone = "America/New_York";
var dateFormatForFileNameString = "'Week of 'yyyy-MM-dd";

function DuplicateSheet() {
  // The code below makes a duplicate of the active sheet
  var ss = SpreadsheetApp.getActiveSpreadsheet()
  SpreadsheetApp.getActiveSpreadsheet().duplicateActiveSheet();

  // The code below will rename the duplicated sheet to YYYY-MM-dd format
  var date = SpreadsheetApp.getActiveSheet( ).getRange("A3").getValue();
  var newDate = new Date(date.setDate(date.getDate()   7));
  var dateString = getDateString_(newDate);
  SpreadsheetApp.getActiveSpreadsheet().renameActiveSheet(dateString);
}

//Function to get Date as a string
function getDateString_(dateValue) {
  return Utilities.formatDate(dateValue, localTimeZone,dateFormatForFileNameString);
}

However, as noted before, I do not know how to incorporate the copy/paste maneuver where I am trying to move the "Budget" from original tab to "Last Week's Budget" in the new/duplicated tab.

CodePudding user response:

Try this:

function DuplicateSheet() {
  const ss = SpreadsheetApp.getActive()
  const sh = ss.getActiveSheet();
  const ns = ss.duplicateActiveSheet();
  const date = new Date(sh.getRange("A3").getValue());
  const col = sh.getRange("E2:E"   sh.getLastRow()).getValues();
  date.setDate(date.getDate()   7);
  ss.renameActiveSheet(Utilities.formatDate(date, "America/New_York", "'Week of 'yyyy-MM-dd"));
  ns.getRange(2,5,col.length,1).setValues(col);
}
  • Related