我要做的是一个工作簿,用户可以从一组项目的下拉列表(Sheet1,列A)中选择,然后在工作表"Dataset“中查找选中的项,然后用从0
到相应的库存总量(Sheet "Dataset”列C)的整数返回该值。
我从@iamblichus获得了一些很棒的代码,这些代码将填充相应的库存数量看他的代码中的下拉列表,这是我使用查询公式查找组库存数量的某种程度上实现的这里。但我不知道如何在两张床单上实现这一点。
发布于 2020-01-29 11:24:40
答案:
扩展https://stackoverflow.com/users/10612011/iamblichus提供的https://stackoverflow.com/a/59946560/11921951代码,您可以指定从其中获取数据的工作表,并使用onEdit()触发器在编辑单元格时自动更改下拉列表。
代码:
将其附加到您提供的示例电子表格中:
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
是在只读模式中调用的,所以不能调用set*()
方法。这包括setDataValidation()
。
根据文档,电子表格服务是受支持的,但是在“Notes”下面它会读到:
只读(可以使用大多数
get*()
方法,但不能使用set*()
)。无法打开其他电子表格(SpreadsheetApp.openById()
或SpreadsheetApp.openByUrl()
)。
参考文献:
https://stackoverflow.com/questions/59959984
复制相似问题