首页 > 解决方案 > 如何根据 Google 表格中的范围自动更新 Google 表单中的下拉列表?

问题描述

我有一个带有下拉菜单的谷歌表单(见下文) 在此处输入图像描述

我在谷歌表上有一个专栏,每天都会更新。

在此处输入图像描述

有什么方法可以自动将 google 表格中的名称链接到 google 表单下拉列表问题 1,以便每次使用其他名称更新工作表时 - google 表单会自动使用下拉列表中的名称进行更新。我想我们需要使用 Google AppScript。任何指引我正确方向的指导将不胜感激。

标签: javascriptgoogle-apps-scriptgoogle-sheetsgoogle-forms

解决方案


一个非常通用的脚本,但您应该能够根据需要对其进行修改

function updateForm(){

  var ss = SpreadsheetApp.openById('----------'); // ID of spreadsheet with names
  var sheet = ss.getSheetByName('Names'); // Name of sheet with range of names
  var nameValues = sheet.getRange('A2:A10').getValues(); // Get name values

  var form = FormApp.openById('---------');  // ID of form
  var formItems = form.getItems();
  var question = formItems[2].asListItem(); // Get the second item on the from 

  var names = []

  for(var x = 1; x < nameValues.length; x++){

    if(nameValues[x][0] != ""){ // Ignores blank cells
     names.push(question.createChoice(nameValues[x][0])) // Create an array of choice objects
   } 
  }
  var setQuestion1 = question.setChoices(names); // Update the question

}

要在编辑工​​作表时更新表单,您可以使用已安装的 onEdit 触发器。通过添加逻辑,您可以将表单的更新限制为仅在编辑特定范围时发生。

在此示例中,仅当对工作表“名称”的 A 列进行了编辑时,表单才会更新

function updateForm(e){

  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var sheet = ss.getActiveSheet();
  var sheetName = sheet.getSheetName();
  var getCol = e.range.getColumn(); 

  if(sheetName == 'Names' && 1){

  var nameValues = sheet.getRange('A2:A10').getValues(); // Get name values

  var form = FormApp.openById('---------');  // ID of form
  var formItems = form.getItems();
  var question = formItems[2].asListItem(); // Get the second item on the from 

  var names = []

  for(var x = 1; x < nameValues.length; x++){

    if(nameValues[x][0] != ""){ // Ignores blank cells
     names.push(question.createChoice(nameValues[x][0])) // Create an array of choice objects
   } 
  }
  var setQuestion1 = question.setChoices(names); // Update the question
  }
}

推荐阅读