Create a new sheet in a Google Sheets with Google Apps Script

Surprisingly I didn't find any clear and quick answer.

So here is my code:

function onOpen() {
    var activeSpreadsheet = SpreadsheetApp.getActiveSpreadsheet();
    var yourNewSheet = activeSpreadsheet.getSheetByName("Name of your new sheet");

    if (yourNewSheet != null) {
        activeSpreadsheet.deleteSheet(yourNewSheet);
    }

    yourNewSheet = activeSpreadsheet.insertSheet();
    yourNewSheet.setName("Name of your new sheet");
}

Finally, note that this new sheet will be automatically the active one.


Here is a simple example:

var name = (new Date()).toLocaleDateString();
SpreadsheetApp.getActiveSpreadsheet().insertSheet(name);

I'd recommend this method.

var ss = SpreadsheetApp.getActiveSpreadsheet();
ss.insertSheet('My New Sheet');

Where 'My New Sheet' is the name you want it to be.