In this blog, I will learn you how to create a new sheet in Google Spreadsheets.
Create new sheets in spreadsheets using Google Apps Script
The below function will create a new sheet in active spreadsheets with the name of “New sheet”
function createSheetInActiveSpreadsheet() {
var sheetName = "New sheet"
var activeSpreadsheet = SpreadsheetApp.getActiveSpreadsheet();
var newSheet = activeSpreadsheet.insertSheet();
newSheet.setName(sheetName);
}
The above function will create a new sheet if that sheet name does not exist but the sheet name is already used in a spreadsheet then the script will throw an error.
In this type of situation, we have to check the sheet name is already in use in spreadsheets if used then we have to delete the old sheet and then create a new sheet.
So here is my code:
function createSheetInActiveSpreadsheet() {
var sheetName = "New sheet"
var newSheet = activeSpreadsheet.getSheetByName(sheetName);
if (newSheet != null) {
activeSpreadsheet.deleteSheet(newSheet);
}
var activeSpreadsheet = SpreadsheetApp.getActiveSpreadsheet();
newSheet = activeSpreadsheet.insertSheet();
newSheet.setName(sheetName);
}