我有一个脚本,可以创建一个新的工作表,其名称基于月份,如2017年10月,每个新月自动生成。
但现在我想要一个按钮,我可以创建具有相同结构的新工作表,其名称基于MMM-yyyy。
我的第一个脚本仅在月份更改时才创建新工作表,但现在我的目的是能够在按下该按钮判断必要时创建它。如何创建按钮不是问题。
因此,如果工作表名称基于以下代码,
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;
}
现在代码需要使用工作表名称作为新名称的参考,增加日期并尊重真实日历,因此如果当前工作表名称是2017年12月,该按钮将创建一个名为Jan-的新工作表2018。所以不再需要像我以前的代码那样与新的Date命令相关。
我开始使用新代码,但我不知道如何创建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);
}
这有什么意义吗? 任何人都可以告诉我如何继续吗?
答案 0 :(得分:0)
我没有包含任何错误处理(因此请确保活动工作表的名称格式为mmm-yyyy),但请查看是否有效
function createNewSheet() {
var monthNames = ["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];
var ss = SpreadsheetApp.getActiveSpreadsheet();
var curMonth = ss.getActiveSheet().getName().split("-")
var nextMonth = new Date(curMonth[1], monthNames.indexOf(curMonth[0])+1, 1);
var name = Utilities.formatDate(nextMonth, 'GMT+12:00', "MMM-yyyy")
ss.setActiveSheet(ss.getSheetByName("template"));
if(!ss.getSheetByName(name)){
ss.duplicateActiveSheet().activate().setName(name)
ss.moveActiveSheet(0);
}
}
答案 1 :(得分:0)
您可以使用标准new Date()
获取下个月的名称,它将处理递增到适当的年份并修改为适当的月份。
此外,请务必检查该名称的工作表是否已存在
function createWorksheet()
{
var monthNames = ["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];
var spreadsheet = SpreadsheetApp.getActiveSpreadsheet();
var monthsToAdd = 1;
var currentDate = new Date();
currentDate.setMonth(currentDate.getMonth() + monthsToAdd);
var sheetName = monthNames[currentDate.getMonth()]+"-"+currentDate.getFullYear();
var sheetsArray = spreadsheet.getSheets();
var creationFlag = false;
//Logger.log(sheetsArray)
for(var itr in sheetsArray)
{
if(sheetsArray[itr].getSheetName() == sheetName)
{
creationFlag = false;
break;
}
else
creationFlag = true;
}
if(creationFlag)
spreadsheet.insertSheet(sheetName);
if(!creationFlag)
Logger.log("Worksheet Exists");
}//createWorksheet