I have a Google Spreadsheet where the active sheet is titled for the month it is being used. For example, the sheet being used in May is called “May.” In my hidden sheets, there are all of the previous months’ sheets as well as a sheet called “Template.” At the 1st of the month, Apps Script is supposed to duplicate the Template, rename it to the current month, then hide the previous months sheet. The purpose of hiding the sheets is so that the team members who access the Spreadsheet don’t have to worry about whether they’re entering data in the wrong month. Once they click their bookmarked link, the first sheet that opens up should be the current months sheet.
Here is my Apps Script code I tried:
function makeNewSheet() {
const months = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];
const d = new Date();
let month = months[d.getMonth()];
let lastMonth = months[d.getMonth() - 1];
var ss = SpreadsheetApp.getActiveSpreadsheet();
var template = ss.getSheetByName("Template");
var copiedSheet = template.copyTo(ss);
copiedSheet.setName(month);
copiedSheet.activate();
ss.moveActiveSheet(1);
var lastMonthSheet = ss.getSheetByName(lastMonth);
lastMonthSheet.hideSheet();
}
I also have a trigger set to execute at 3am on the 1st of the month. I’ve tried adjusting the execution time as I thought maybe there was some funky stuff happening with the new Date() timezone but that didn’t change the result. The execution is claiming a 0% error rate.
When I was first testing out my code, my spreadsheet was set up so that the only unhidden sheet was the current months sheet. When I tried to run the code, it would give me an error and say that it couldn’t hide the sheet because there can’t be zero unhidden sheets. I then figured out that if I just left a blank sheet there just called “Sheet 3,” the code would sometimes run correctly, although it would give me a 0% error rate.
Here’s what happens with my current set up. On the 1st of the month, the script successfully duplicates the template, renames it to the current month, then it hides both the previous month and the current months sheet. So when you visit the spreadsheet, the only viewable sheet is the blank sheet. The strange thing is that this doesn’t happen 100% of the time. Sometimes other wonky things happen like the code will run exactly how I want it to, then I check on it an hour later and the current months sheet is somehow hidden. Or sometimes it’ll hide the current month instead of hiding the previous month. Plz help!!
jonzyyyy is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.