在Google Apps脚本中创建动态下拉列表

Car*_*jas 3 google-apps-script

我想使用Google Apps脚本动态更改Google电子表格的单元格验证功能中候选列表的值.我需要从其他电子表格中获取值.

Fra*_*o B 5

如果我理解正确的话,这是我一直在努力解决的问题.通常我使用importRange"本地化"远程列表,但这还没有在新的Google电子表格中使用...所以你可以尝试更直接的方法,如下所示:

function setDropdown(){   
   var sourceSS = SpreadsheetApp.openById('yourSpreadsheetID');  // replace yourSpreadsheetID with the value in the sheet URL
   var ss = SpreadsheetApp.getActive();
   // get the range where the dynamic dropdown list is kept in the source spreadsheet
   var dynamicList = sourceSS.getSheetByName('Dropdown List Sheet').getRange('A2:A');   // set to your sheet and range
   // define the dropdown/validation rules
   var rangeRule = SpreadsheetApp.newDataValidation().requireValueInRange(dynamicList).build();
   // set the dropdown validation for the row
   ss.getRange('sheet 1!A5:A10').setDataValidation(rangeRule); // set range to your range
}
Run Code Online (Sandbox Code Playgroud)

我怀疑上述内容在新的Google电子表格中无效.以下修改将范围转换为值列表.这是在一个简短的清单上测试,并完成工作......

function setDropdown(){   
   var sourceSS = SpreadsheetApp.openById('yourSpreadsheetID');  // replace yourSpreadsheetID with the value in the sheet URL
   var ss = SpreadsheetApp.getActive();
   // get the range where the dynamic dropdown list is kept in the source spreadsheet
   var dynamicList = sourceSS.getSheetByName('Dropdown List Sheet').getRange('A2:A10');   // set to your sheet and range
   var arrayValues = dynamicList.getValues();
   // define the dropdown/validation rules
   var rangeRule = SpreadsheetApp.newDataValidation().requireValueInList(arrayValues);
   // set the dropdown validation for the row
   ss.getRange('sheet 1!A5:A10').setDataValidation(rangeRule); // set range to your range
}
Run Code Online (Sandbox Code Playgroud)

  • 请参阅替代方案...可能requireValueInRange()可能无法在新版Google电子表格中运行.使用值列表似乎可以完成这项工作. (2认同)