首页 > 解决方案 > Google 电子表格值使用 Google Apps 脚本推送到表单,但按字母顺序排序

问题描述

我有一个 Google Apps 脚本,它可以获取电子表格中特定列中的数据,并将其推送到 Google 表单中的下拉菜单中。

这一切都完美无缺。

但是,我正在尝试通过脚本对数据进行排序,以便在将其推送到表单之前按字母顺序(A --> Z)对其进行排序。

电子表格中的数据没有排序,我不能只在电子表格中排序,因为数据一直在添加。

这是有效的 Google Apps 脚本,但排序除外:

function updateClientForm(){
  // call your form and connect to the drop-down item
  var form = FormApp.openById("1qszM48QILtnf-2QZa078ypqhjYHdB-VK2c0VMJDrsXo");

  //Inspect the element on the form to find the ID value
  var clientnamesList = form.getItemById("449574637").asListItem();


// identify the sheet where the data resides needed to populate the drop-down
  var ss = SpreadsheetApp.getActive();
  var clientnames = ss.getSheetByName("Client Names with ID");

  // grab the values in the first column of the sheet - use 2 to skip header row 
  var namesValues = clientnames.getRange(2, 1, clientnames.getMaxRows() - 1).getValues();

  var customerNames = [];

  // convert the array ignoring empty cells
  for(var i = 0; i < namesValues.length; i++)    
    if(namesValues[i][0] != "")
      customerNames[i] = namesValues[i][0];

  // populate the drop-down with the array data
  clientnamesList.setChoiceValues(customerNames);

}

有任何想法吗?提前致谢!

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

解决方案


Google Apps 脚本基于 javascript,因此您可以访问几乎所有可以在 javascript 中执行的操作。

namesValues 是一个数组,javascript 数组带有内置的排序函数

sortedNamesValues = namesValues.sort();

推荐阅读