我的用例是我将有一个在电子表格中定义的流程规则列表。那是后端的东西。最终用户将复制一个 Google 文档,该文档将具有基于规则电子表格内容的动态菜单。我编写了一个 onOpen 函数,该函数从电子表格中读取并创建为工作表命名的菜单项。这些菜单项将触发处理工作表中的规则的函数。
我的问题是 onOpen 函数在从脚本编辑器触发时正确运行,但在打开文档时不会触发。通过玩弄注释位,我确定 SpreadsheetApp.openById() 命令导致 onOpen 函数在初始文档加载时失败。它会在不使用该命令时运行。
我已经在函数内部和外部设置了工作表定义,结果没有区别,所以我相信下面的代码应该可以工作。确实如此,只是在打开文档时不会自动发生。很有趣,对吧?所以这是我的代码文档:
https://docs.google.com/document/d/1dQb5RYntMsbTIxDCh6uEoNur3oOlVisxP7hD_sK3Fsk/edit
这是定义菜单项的电子表格:
https://docs.google.com/spreadsheet/ccc?key=0AjR3e-R75aP8dHR0WWpGNF9vdEhvcy12eHJTMmF3aXc#gid=0
// from this spreadsheet, I want function names based on the sheet names
var ss = SpreadsheetApp.openById("0AjR3e-R75aP8dHR0WWpGNF9vdEhvcy12eHJTMmF3aXc");
var sheets = ss.getSheets();
function onOpen() {
var menu = DocumentApp.getUi().createMenu("Menu Title");
// dynamic menu based on tabs in spreadsheet
for (sheet in sheets) {
var thisCaption = sheets[sheet].getName();
var thisFunction = "sheet_" + sheet;
menu.addItem(thisCaption, thisFunction);
}
menu.addToUi();
}
// I precreate dummy functions based on sheet number
function sheet_0() { process_sheet(0); }
function sheet_1() { process_sheet(1); }
function sheet_2() { process_sheet(2); }
function sheet_3() { process_sheet(3); }
function sheet_4() { process_sheet(4); }
function sheet_5() { process_sheet(5); }
function sheet_6() { process_sheet(6); }
function sheet_7() { process_sheet(7); }
function sheet_8() { process_sheet(8); }
function sheet_9() { process_sheet(9); }
function process_sheet(sheetNum) {
var thisSheet = sheets[sheetNum];
// at this point I do some processing based on the contents of the sheet
// for the sake of example, I'll just set the document name to the sheet name
var sheetName = thisSheet.getName();
DocumentApp.getActiveDocument().setName(sheetName);
}