下拉列表自动生成基于总计的范围



我正在尝试创建一个工作表,供用户从下拉列表中选择项目数量,并引用总库存数量。

我很幸运地找到了一个脚本来填充引用范围但必须生成该范围中的所有项目的下拉列表。

我希望下拉列表(B 列(引用总袜子(C 列(并填充下拉列表,而无需我在 D-Z 列中呈现范围。

示例表

如果我理解正确,您想在 B 列的每个单元格中创建一个下拉列表,其选项是从 0 到 C 列中相应Stock Quantity的整数。

如果是这种情况,您可以将以下函数复制到绑定到电子表格的脚本中:

function generateDropdowns() {
var ss = SpreadsheetApp.getActive(); // Get the spreadsheet bound to this script
var sheet = ss.getSheetByName("Working with script"); // Get the sheet called "Working with script" (change if necessary)
// Get the different values in column C (stock quantities):
var firstRow = 2;
var firstCol = 3;
var numRows = sheet.getLastRow() - firstRow + 1;
var stockQuantities = sheet.getRange(firstRow, firstCol, numRows).getValues();
// Iterate through all values in volumn:
for (var i = 0; i < stockQuantities.length; i++) {
var stockQuantity = stockQuantities[i][0];
var values = [];
// Create the different options for the dropdown based on the value in column C:
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:
var dropdownCell = sheet.getRange(i + firstRow, 2).setDataValidation(rule);
}
}

此脚本执行以下操作(检查内联注释以获取更多详细信息(:

  • 首先,它通过 getRange 和 getValue 获取 C 列中的所有库存数量。
  • 对于每个库存数量,它会创建一个数组,其中包含 B 列中相应下拉列表的不同选项。
  • 从每个数组中,它使用 newDataValidation 和 requireValueInList(values( 创建下拉列表,然后使用 setDataValidation 将其设置为 B 列中的相应单元格。

我希望这有什么帮助。

最新更新