如何使用Apps脚本获取Google表单目标的电子表格选项卡名称

时间:2017-05-21 17:25:50

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

我在Google电子表格的列中有一个Google表单列表。我需要获取电子表格选项卡的名称,该选项卡是每个表单的响应目标。

在表单列表中运行的for循环中,我正在使用

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作为表单列表中每个单元格的项目传递。

但这给了我一个错误&#34;找不到具有给定ID的项目,或者您无权访问它。&#34;这发生在Line1上。

错误的第二部分(&#34;您没有权限......&#34;)不正确,因为我是包含表单列表的表单的所有者以及表单本身。

有没有办法可以得到这个?

2 个答案:

答案 0 :(得分:2)

不幸的是,方法getDestinationId()返回电子表格的id,而不是表单绑定的特定表格。我建议你做的是存储工作表名称或ID以及您列出的表单ID,然后您可以循环这些行并根据需要检索相应的工作表名称/ ID。

答案 1 :(得分: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())生成表单目标。这会按名称创建一个标签&#39;表单回复xx&#39;这总是电子表格中的第一个标签。因此,通过扩展,上述代码只有在完成对工作表中选项卡顺序的任何更改(有意,或通过设计或意外)之前运行时才能正常工作。

另请注意,我强制使用这样的单独函数,因为包含form.setDestination(FormApp.DestinationType.SPREADSHEET,ss.getId())的函数会给出一个强制表格的错误重装。发生这种情况时,destinationTabName()函数中包含的功能实际上是将工作表中的早期选项卡注册为工作表[0]。

但总的来说,这个解决方法现在适用于我。

注意:在非代码区域,当我说&#34; Sheet&#34;时,我指的是整个Google表格工作簿。 &#34;标签&#34; =工作簿的各个选项卡。