使用app脚本在电子表格菜单中使用addItem参数的函数

时间:2017-02-07 16:21:15

标签: google-apps-script google-sheets

我需要在每次打开电子表格时检查电子表格中的可用工作表,并制作一个列表插件,通过单击项目列表转到特定工作表

工作表的数量很大,并通过工作

动态添加

我正在阻止当前使这个“虚拟”函数获取参数所以,当被调用它时应该按索引打开工作表

function onOpen() {
  var monthPlanShortcuts = SpreadsheetApp.getUi().createMenu("Month Plan Shortcuts");
  var gotoSheet = SpreadsheetApp.getUi().createMenu("Go to sheet");
  // get properties to know who is the editor
  var userProperties = PropertiesService.getUserProperties();
  var sheets = SpreadsheetApp.getActiveSpreadsheet().getSheets();
  if (sheets.length > 1) {
    for (var index = 0; index< sheets.length;index++)
    {
      var currentIndex = userProperties.setProperty("index",index);
      gotoSheet.addItem(sheets[index].getName(),"dummy");
    }
  }
  monthPlanShortcuts
    .addItem('View Current Week Plan', 'gotoCurrentWeek')
    .addItem('Go to Specific Week', 'gotoSpecificWeek')
  .addSeparator()
  .addSubMenu(gotoSheet)
  .addToUi();
}

任何建议?

1 个答案:

答案 0 :(得分:0)

有一个骇人听闻的解决方法:

动态创建顶层函数,然后在添加菜单项时引用它们。

示例:

/**
 * @OnlyCurrentDoc
 */
function onOpen() {
  let menu = SpreadsheetApp.getUi().createMenu("Dynamic entries");
  let ss = SpreadsheetApp.getActiveSpreadsheet();
  for (var sheet of ss.getSheets()) {
    let id = sheet.getSheetId();
    let funName = "dynamicFun" + id;
    menu.addItem(sheet.getName() + "(" + id + ")", funName)
  }
  menu.addToUi();
}

for (var sheet of SpreadsheetApp.getActiveSpreadsheet().getSheets()) {
  let id = sheet.getSheetId();
  let funName = "dynamicFun" + id;
  this[funName] = function() { myRealFun(id); };
}

function myRealFun(id) {
  SpreadsheetApp.getUi().alert("" + id + " was pressed");
}