Google Sheets – Script to Create a New Worksheet

google sheetsgoogle-apps-script

I want to be able to have a button on a Google Spreadsheet. The user clicks on the button and a new worksheet is created based on a template (or blank existing worksheet). The new worksheet should have the name of the current date.

How can I achieve this?

Best Answer

Here's a script that you can tweak further for your use case. It adds a couple of custom new commands to the menu when the spreadsheet opens:

custom

The commands copy the content of the currently active sheet to the new one, named in the ISO date format, e.g., 2015-05-15.

function onOpen() {
  var menu = [{name: "New Sheet as First", functionName: "newSheet"}, {name: "New Sheet as Last", functionName: "newSheetLast"}];
  SpreadsheetApp.getActiveSpreadsheet().addMenu("Custom", menu);
}

function newSheet() {
  var sheetName = formatDate();
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var templateSheet = ss.getActiveSheet();
  ss.insertSheet(sheetName, 0, {template: templateSheet});
}

function newSheetLast() {
  var sheetName = formatDate();
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var templateSheet = ss.getActiveSheet();
  ss.insertSheet(sheetName, ss.getSheets().length, {template: templateSheet});
}

function formatDate() {
  var month, day, d = new Date();
  month = ('0'+(d.getUTCMonth()+1)).slice(-2);
  day = ('0'+d.getUTCDate()).slice(-2);
  return d.getUTCFullYear()+'-'+month+'-'+day;
}