Home > Enterprise >  Copy Google Sheet from Master, Rename, Edit Cell and Move Position
Copy Google Sheet from Master, Rename, Edit Cell and Move Position

Time:04-10

I'm trying to create a script that creates a new sheet from a master sheet everyday, renames it to the current date, edits A1 to show the current date, hides the master and moves the sheet to the first position on the tabs at the bottom. Very stuck, please help!

function master() {

 const pattern = 'master';
 var source = SpreadsheetApp.getActiveSpreadsheet();
 var date = getDates();
 var master = source.getSheetByName(pattern);
 var current = source.getSheetByName(date);

 source.insertSheet(date);

 master.copyTo(current);
  
 master.hideSheet();
  
 current.getRange("A1").setValue(getDates()).moveActiveSheet(1);
 
}

function getDates() {
 
  var today = new Date();
 
  var today_month = addZero(today.getMonth() 1)
  var today_day = addZero(today.getDate())
  var today_year = addZero(today.getYear() 1900)

  var today_date =  today_day.toString()   "/"   today_month.toString()   "/"   today_year.toString()
  
  return [today_date]

}

function addZero(i) {
  if (i < 10) {
    i = "0"   i;
  }
  return i;
}

CodePudding user response:

I see that you tried to make your own function to convert a date to a string. Since you wanted a standard european format, it is easier to use the method Date.toLocaleDateString()

Another improvement is that Sheet.copyTo() returns the new sheet, so you can chain some more methods like activate() or setName() and finally assign the result to a variable.

This should do what you want:

function master() {
  const pattern = 'master';
  const locale = "en-GB"; // date format dd/mm/yyyy 

  var today = new Date()
  var title = today.toLocaleDateString(locale);

  // find the master sheet
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var master = ss.getSheetByName(pattern);

  // make a copy, set as active, and rename
  var current = master.copyTo(ss).activate().setName(title)

  // rearrange tabs and hide master
  ss.moveActiveSheet(1);
  master.hideSheet();

  // put the date in A1 (as a date format, not text)
  current.getRange("A1").setValue(today)  
}
  • Related