2017-05-21 28 views
2

我在Google電子表格的一列中列出了Google表單。我需要獲取每個表單響應目標的電子表格選項卡的名稱。如何使用Apps腳本獲取Google表單目標的電子表格名稱

在該的形式在列表上運行循環,我使用

for(i = 1; i < length-of-thelist, i++) { 

var form = FormApp.openByUrl(url); //Line1 
var destId = form.getDestinationId(); //Line2 
var sheetName = SpreadsheetApp.openById(destId).getSheetName(); //Line3 
//..... other lines to print the sheet name ...... 

} 

在第1行,我傳遞作爲URL的形式列表的每個單元格的項目。

但是這給了我一個錯誤「沒有找到給定ID的項目,或者您沒有權限訪問它。」這發生在Line1上。

錯誤的第二部分(「您沒有權限...」)不是真實的,因爲我是表單的所有者,它包含表單列表以及表單本身。

有沒有辦法讓我得到這個?

+0

我會避免在變量名稱破折號 - 它使代碼相當尷尬閱讀。 – Ryan

+0

謝謝瑞恩。感謝您的反饋! – Krishna

+0

感謝Rubén對編輯。 – Krishna

回答

2

不幸的是,方法getDestinationId()返回電子表格的id,而不是表單綁定到的特定工作表。我建議你做的是將表單名稱或ID與表單id一起存儲,然後可以遍歷這些行並根據需要檢索適當的表單名稱/ ID。

+0

謝謝Dimu。我進一步研究了這一點,發現有一個答案。請參閱,我試圖回答我自己的問題(不知道這是否是一種好的做法,儘管:))))。 – Krishna

1

我已經建立了這個,似乎工作。

function destinationTabName() { 
    var master_file = DriveApp.getFileById('1zwTluWabUdHxxxxxxxxxxxxxxx'); //reading the active spreadsheet 
    var master_doc_id = master_file.getId(); //getting the file id 


    var ss = SpreadsheetApp.openById(master_doc_id); 
    SpreadsheetApp.setActiveSpreadsheet(ss); 


    var sheet = ss.getSheetByName("Sheet1"); // Let us assume Sheet1 is the name of the tab in which we want to output the name of the tab which is the form destination 
    var sheetArray = sheet.getDataRange().getValues(); 



    var sheets = ss.getSheets(); 
    sheet.getRange(sheetArray.length+1, column#).setValue(sheets[0].getName()); 

} 

請注意,片材[0]的工作原理在這種情況下,因爲我生成使用form.setDestination形式目的地(FormApp.DestinationType.SPREADSHEET,ss.getId());這將通過名稱「Form Responses xx」創建一個標籤,它總是電子表格中的第一個標籤。因此,通過擴展,上述代碼僅在工作表中的選項卡順序發生任何更改(有意,或有意或無意)完成之前運行時才能正常工作。

另外請注意,我被迫使用這樣一個單獨的函數,因爲包含form.setDestination(FormApp.DestinationType.SPREADSHEET,ss.getId())的函數提供了一個錯誤,強制工作表重新加載。發生這種情況時,destinationTabName()函數中包含的功能實際上是在工作表中將較早的選項卡記錄爲工作表[0]。

但總的來說,該解決方法現在適用於我。

注意:在非代碼區,當我說「表」時,我的意思是整個Google表格工作簿。 「Tab」=工作簿的單個選項卡。

相關問題