2013-06-19 45 views
0

我的用例是我將擁有一個在電子表格中定義的過程的規則列表。這是後端的東西。最終用戶將複製一份Google文檔,該文檔將具有基於規則電子表格內容的動態菜單。我寫了一個onOpen函數,它可以從電子表格中讀取並創建爲表單命名的菜單項。這些菜單項將觸發一個處理表單中規則的函數。訪問電子表格時,Google Doc 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); 
    } 

回答

2

您不能訪問外部文件(電子表格否則)從一個onOpen觸發的功能。由於此功能自動運行,無需任何用戶授權。它無法訪問可能需要授權的API。

我不知道任何解決方法,我想你只需要改變你的方式。也許從一個函數中設置這個動態菜單,用戶點擊你從onOpen創建的固定菜單。因爲當用戶點擊一個功能時,授權彈出窗口會顯示給他,然後你的腳本可以在他的權限下運行,並可以完成他授權的所有事情,這意味着要打開此電子表格,必須與他共享,只有當你有其他用戶比你自己時纔有意義:)

+0

謝謝Henrique。雖然我不喜歡「點擊這個菜單,然後回到同一個菜單,因爲現在它不同」的流程,但這似乎是將會發生的事情。 – ccombs

相關問題