Javascript 在Google Sheets Apps脚本中,如何检查工作表是否存在,以及是否存在';不要加一个
我正在创建一个电子表格,根据输入的日期对事件进行排序。我已经成功地让程序添加了一个新的工作表,其中包含我想要复制的事件内容,但是我无法添加到脚本中以允许两个选项。我的目标是让它像这样:Javascript 在Google Sheets Apps脚本中,如何检查工作表是否存在,以及是否存在';不要加一个,javascript,google-apps-script,google-sheets,try-catch,Javascript,Google Apps Script,Google Sheets,Try Catch,我正在创建一个电子表格,根据输入的日期对事件进行排序。我已经成功地让程序添加了一个新的工作表,其中包含我想要复制的事件内容,但是我无法添加到脚本中以允许两个选项。我的目标是让它像这样: var sheet2 = ss.getSheetByName(A2); if( ss.getSheetByName(A2) == null) { //if returned null means the sheet doesn't exist, so create it var val = Utiliti
var sheet2 = ss.getSheetByName(A2);
if( ss.getSheetByName(A2) == null)
{
//if returned null means the sheet doesn't exist, so create it
var val = Utilities.formatDate(new Date(A2), "GMT+1", "MM/dd/yyyy");
ss.insertSheet(val, ss.getSheets().length, {template: templateSheet});
sheet2 = ss.insertSheet(A2);
}
//Rest of the behavior...
选项1:工作表已存在
. A2:D2单元格将从模板工作表复制到标题与单元格A2中日期相同的工作表中。
. A2:D2将从模板工作表中清除,以留下空白画布
选项2:图纸不存在
. 使用模板工作表作为新工作表的模板,将复制所有信息,A2中的日期作为新工作表的名称。
. A2:D2将从模板工作表中清除,以留下空白画布
我尝试使用try-catch语句,尝试查找工作表,如果不起作用,catch将使用新名称创建工作表。我得到错误“一张名为“\uuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuu
我还尝试了一个if-else语句,该语句具有类似的思想,指出如果getSheetByName不起作用,它将创建一个工作表,否则它将设置一个新的活动工作表。这个有同样的错误
至于我的代码,我将展示它,但我必须警告它有点笨重(无论出于何种原因,它都不会确认try-catch语句中的变量,除非我重述它们)
如果有人知道为什么这不起作用,我很想知道。谢谢 当不存在具有该名称的工作表时,函数
getSheetByName
返回null
。如果您以这种方式实现代码,我认为会更容易
代码应该是这样的:
var sheet2 = ss.getSheetByName(A2);
if( ss.getSheetByName(A2) == null)
{
//if returned null means the sheet doesn't exist, so create it
var val = Utilities.formatDate(new Date(A2), "GMT+1", "MM/dd/yyyy");
ss.insertSheet(val, ss.getSheets().length, {template: templateSheet});
sheet2 = ss.insertSheet(A2);
}
//Rest of the behavior...
这看起来应该是可行的,不过当我实现它时,同样的错误仍然存在。出于某种原因,当它检查ss.getSheetByName(A2)==null时,它没有收到我想要的答案。