I love using Google Form for collecting data and surveys. At times, I wish a feature, where inputs for Drop Down List, Checkbox or Multiple choice could be feed from excel sheet. This will help us when form itself is dependent on values from some other source.
We can achieve it with a simple google script. The script is executed from spreadsheet. It updates the Google form with a trigger set 'on change' on spreadsheet.
In below script, I take an existing google form and modify one of the drop down item in it. The values for this drop down item is fed from a named range in current active sheet.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function editForm() { | |
var form = FormApp.openById('<YOUR_FORM_ID_GOES_HERE>'); | |
// Following line just logs form title in logger. | |
// Helps in troubleshooting. :) | |
Logger.log('Form Title is '+ form.getTitle()); | |
// Gets all items inside the form. | |
allItems = form.getItems(); | |
Logger.log(' Total items in this form '+ allItems.length) | |
// Setting a value. Not a great idea to do though. | |
empLocItemId=0; | |
// Iterate through all items in form | |
for (i=0; i < allItems.length ; ++i) { | |
itemTitle = allItems[i].getTitle(); | |
Logger.log('Item Title '+ itemTitle); | |
// Checking if item's title matches the one | |
// which you want to change. I prefer this way | |
// instead of directly using form.getItemById('...') | |
if (itemTitle == 'Employee Location') { | |
empLocItemId = allItems[i].getId(); | |
} | |
} | |
// Checking in case item to edit was not found. | |
if (empLocItemId == 0) { | |
return; | |
} | |
// Casting item to listItem. Should use .asCheckBoxItem() | |
// if using checkbox or .asMultipleChoiceItem() if using | |
// multiple choice. | |
empLocItem = form.getItemById(empLocItemId).asListItem(); | |
// Getting object of current spreadsheet from which we need | |
// to get values for drop down list. | |
ss = SpreadsheetApp.getActive(); | |
// Getting a known named range from spreadsheet object. | |
empLocRange = ss.getRangeByName('EmployeeLocations'); | |
empLocs = empLocRange.getValues(); | |
empLocs.sort() | |
// Creating choice Array. | |
var empLocChoices = [] | |
for (i=0; i < empLocs.length; ++i) { | |
empLoc = empLocs[i][0].toString().trim(); | |
if (!(empLoc=='')) { | |
empLocChoices.push(empLocItem.createChoice(empLoc)); | |
} | |
} | |
// Setting the choice array to drop down item. | |
empLocItem.setChoices(empLocChoices); | |
} |