(Google API)动态工作表和单元格参考中的工作表创建脚本名称

时间:2016-03-19 01:18:48

标签: javascript google-apps-script google-sheets

我需要帮助我的功能,应该:

  • 复制隐藏表
  • 确保不存在重复的命名工作表
  • 从单元格引用中动态命名副本
  • 显示工作表副本

这是我到目前为止所做的,但我对语法不太清楚: 修复:(错误的'='代替'=='if if语句)

    function checkSheetName(name)
{
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var allSheets = ss.getSheets();
  var cSheets = ss.getNumSheets();

  for(i = 1; i < cSheets; i++)
  {
  var currentSheetName = allSheets[i].getName();
  if(currentSheetName == name);
  return true;
  }
  return false;
}
function createNextMonth()
{
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var tz = ss.getSpreadsheetTimeZone();
  var allSheets = ss.getSheets();
  var dateSheet = ss.getSheetByName("Start Date:");
  var currentSheet = ss.getActiveSheet();
  var startRange;

  // Check where to get the cell references from
  if(dateSheet != currentSheet)
    startRange = currentSheet.getRange(4,7);
  else
    startRange = currentSheet.getRange(4,7);

  var startDate = new Date(startRange.getValue());
    // Format date to MONTH (YYYY)
  var newSheetName = Utilities.formatDate(startDate, tz, "yyyy-MMMMM-dd'T'HH:mm:ss'Z'");
  if(!newSheetName)
    // Error making name
    return false;

  if(!checkSheetName(newSheetName))
    // Error duplicate
    // Inform user
    return false;

    // Locate the template sheet
  var templateSheet = ss.getSheetByName("TEMPLATE");
  if(!templateSheet)
    // Error missing
    // Couldn't find template
    return false;

    // Set the active sheet to the template sheet
  ss.setActiveSheet(templateSheet);
    // Duplicate active sheet
  ss.duplicateActiveSheet();

  // Unsure how to locate duplicated sheet

  ss.renameActiveSheet(newSheetName);

  // Unsure how to set new sheet cell B3 to startDate

  return true;
}

更新:忘记提及问题是它似乎没有获得正确的日期值,或者获得正确的单元格。

更新2:更正了修复问题的循环上的简单语法错误。

1 个答案:

答案 0 :(得分:1)

这将是一个良好的开端r.e.检查重复的工作表并将新副本设置为有效(信用https://ctrlq.org/code/19973-duplicate-sheet-google-spreadsheets):

function cloneGoogleSheet() {

  var name = "labnol";
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var sheet = ss.getSheetByName('Template').copyTo(ss);

  /* Before cloning the sheet, delete any previous copy */
  var old = ss.getSheetByName(name);
  if (old) ss.deleteSheet(old); // or old.setName(new Name);

  SpreadsheetApp.flush(); // Utilities.sleep(2000);
  sheet.setName(company);

  /* Make the new sheet active */
  ss.setActiveSheet(sheet);

}

这样的事情可能有助于将单元格值用作名称:

  var bb = ss.getSheetByName("sheetnamehere");
  var newsheetname = bb.getRange("j6");
  var newsheetvalue = newsheetname.getValue();
  sheet.setname(newsheetvalue)