I have a script which creates a new sheet with a name based on month-year, like Oct-2017, automatically every new month.
But now I'd like to have a button, where I can create new sheets with the same structure, with names based on the MMM-yyyy.
My first script creates a new sheet only when the month changes, but now my intention is to be able to create it when I judge necessary by pressing that button. How to create a button is not a problem.
So, if before the sheet name was based on the following code,
function checkSheetName() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheetName = formatDate(); // load the current 'Month-Year'
try {
ss.setActiveSheet(ss.getSheetByName(sheetName)); // try to set 'sheetName' as active sheet
} catch (e) { // if returns error,
createNewMonthSheet(); // creates a new sheet
}
function createNewMonthSheet() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheetName = formatDate(); // load the current 'Month-Year'
ss.insertSheet(sheetName, 2); // creates a new sheet on the left side, after 2 existing sheets
}
function formatDate() {
var monthNames = ["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];
var monthNumber = Utilities.formatDate(new Date(), 'GMT+12:00', "M");
var yearNumber = Utilities.formatDate(new Date(), 'GMT+12:00', "yyyy");
return monthNames[monthNumber-1]+'-'+yearNumber;
}
now the code needs to use the Sheet Name as a reference for the new name, increasing the date and respecting a real calendar, so if the current sheet name is Dec-2017, the button will create a new sheet called Jan-2018. So no need anymore to be related to the new Date command like my previous code.
I started a new code, but I don't know how to create the var nameOfNextMonth:
function createNewSheet() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var currentMonth = ss.getActiveSheet().getName();
var nameOfNextMonth = **[currentMonth+1]**;
ss.setActiveSheet(ss.getSheetByName("template"));
var newSheet = ss.duplicateActiveSheet();
newSheet.activate();
ss.moveActiveSheet(0);
newSheet.setName(nameOfNextMonth);
}
Is that making any sense? Could anyone give me any idea how to proceed?