The following code will create sheets based on the number of days in a given month.
Code
// globals
var JAN = "January";
var FEB = "February";
var MAR = "March";
var APR = "April";
var MAY = "May";
var JUN = "June";
var JUL = "July";
var AUG = "August";
var SEP = "September";
var OCT = "October";
var NOV = "November";
var DEC = "December";
var ss = SpreadsheetApp.getActiveSpreadsheet();
function onOpen() {
SpreadsheetApp.getUi().createMenu("Create sheets")
.addItem(JAN, "createSheetsJan")
.addItem(FEB, "createSheetsFeb")
.addItem(MAR, "createSheetsMar")
.addItem(APR, "createSheetsApr")
.addItem(MAY, "createSheetsMay")
.addItem(JUN, "createSheetsJun")
.addItem(JUL, "createSheetsJul")
.addItem(AUG, "createSheetsAug")
.addItem(SEP, "createSheetsSep")
.addItem(OCT, "createSheetsOct")
.addItem(NOV, "createSheetsNov")
.addItem(DEC, "createSheetsDec")
.addSeparator()
.addItem("Delete sheets", "deleteSheets")
.addToUi();
}
function createSheetsJan() {
createMonth(JAN);
}
function createSheetsFeb() {
createMonth(FEB);
}
function createSheetsMar() {
createMonth(MAR);
}
function createSheetsApr() {
createMonth(APR);
}
function createSheetsMay() {
createMonth(MAY);
}
function createSheetsJun() {
createMonth(JUN);
}
function createSheetsJul() {
createMonth(JUL);
}
function createSheetsAug() {
createMonth(AUG);
}
function createSheetsSep() {
createMonth(SEP);
}
function createSheetsOct() {
createMonth(OCT);
}
function createSheetsNov() {
createMonth(NOV);
}
function createSheetsDec() {
createMonth(DEC);
}
function deleteSheets() {
var shs = ss.getSheets();
shs.forEach( function (s, i) {
i > 0 ? ss.deleteSheet(shs[i]) : null;
});
}
function createMonth(month) {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var tmp = ss.getSheetByName('Sheet1');
var tmz = ss.getSpreadsheetTimeZone();
var cnt = 1;
var year = new Date().getYear();
//https://stackoverflow.com/a/13566675/1536038
month = new Date(Date.parse(month + " 1," + year)).getMonth();
var date = new Date(year, month, 1);
while (date.getMonth() === month) {
ss.insertSheet(Utilities.formatDate(date, tmz, "EEE dd MMM"), cnt, {template: tmp});
date.setDate(date.getDate() + 1);
cnt++;
}
}
Explained
- First the code create global variables that can be used throughout the script.
- Then it will create a new menu option, with all months added (plus an extra option to delete all sheets).
- Once a selection is made from the menu, the script will plough through the month, whilst creating the sheets in the desired naming format, see the
createMonth
function
- you can assign a template sheet if you want to
Add this script to your script editor (Tools > Script editor...) and press save. Now press the bug button to authenticate the script in your environment. Window appears, telling you the script is unsave, but scroll down and click the link to the left and approve the script nonetheless. Now the onOpen function will be executed and a new menu item will appear.
Hope this helps and good luck creating those sheets !!