【问题标题】:Fill Dropdown from Selected Item填充所选项目的下拉列表
【发布时间】:2020-01-29 03:06:11
【问题描述】:

我正在尝试制作的是一个工作簿,用户可以从一组项目(Sheet1,A 列)的下拉列表中进行选择,然后 B 行在工作表“数据集”中查找所选项目并返回该值与整数从0 转到(表“数据集”C 列)中相应的库存总量

here is a Sample spreadsheet

我从@iamblichus 获得了一些很棒的代码,这些代码将填充相应库存数量的下拉列表 see his code here 我已经使用查询公式在某种程度上实现了Here 来查找集团库存数量。不过,我不确定如何在两张纸上实现这一点。

【问题讨论】:

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


    【解决方案1】:

    答案:

    扩展 @iamblichus 提供的代码 here,您可以指定从中获取数据的表格,并使用 onEdit() 触发器在编辑单元格时自动更改下拉列表。 em>

    代码:

    将此附加到您提供的示例电子表格:

    function onEdit(e) {
      var ss = SpreadsheetApp.getActive(); // Get the spreadsheet bound to this script
      var dataSetSheet = ss.getSheetByName("Dataset"); // Get the sheet called "Working with script" (change if necessary)
      var fillSheet = ss.getSheetByName("Sheet 1");
      
      // Get the different values in column C (stock quantities):
      var firstRow = 3;
      var firstCol = 3;
      var numRows = dataSetSheet.getLastRow() - firstRow + 1;
      var stockQuantities = dataSetSheet.getRange(firstRow, firstCol, numRows).getValues();
      var stockNames = dataSetSheet.getRange(firstRow, firstCol - 1, numRows).getValues();
      
      // Iterate through all values in column:
      for (var i = 0; i < stockQuantities.length; i++) {
        Logger.log(stockNames);
        Logger.log(stockQuantities);
        var stockQuantity = stockQuantities[i][0];
        var values = [];
        // Create the different options for the dropdown based on the value in column C:
        
        if (stockNames[i] == e.value) {
          for (var j = 0; j <= stockQuantity; j++) {
            values.push(j);
          }   
          // Create the data validation:
          var rule = SpreadsheetApp.newDataValidation().requireValueInList(values).build();
          // Add the data validation to the corresponding cell in column B:
          fillSheet.getRange(e.range.getRow(), 2).clear();
          var dropdownCell = fillSheet.getRange(e.range.getRow(), 2).setDataValidation(rule);
        }
      }
    }
    

    注意事项:

    我把它作为一个onEdit() 函数,因为SpreadsheetApp 在自定义函数内部时在Read Only mode 中被调用,所以不能调用set*() 方法。这包括setDataValidation()

    根据文档,电子表格服务受支持,但在“注释”下显示:

    只读(可以使用大多数get*() 方法,但不能使用set*())。 无法打开其他电子表格(SpreadsheetApp.openById()SpreadsheetApp.openByUrl())。

    参考资料:

    【讨论】:

    • 嘿,我还有一些项目不需要下拉菜单来选择项目类型(A 列) 是否可以让另一个脚本运行并更新这些下拉菜单(B 列)?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-12-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-02-18
    • 1970-01-01
    • 2014-04-10
    相关资源
    最近更新 更多