spy*_*3rr 2 google-sheets google-apps-script
有没有办法从范围中得到一个子范围?
即。
var ss = SpreadsheetApp.getActiveSpreadsheet();
var fullRange = ss.getRange("A:P");
Run Code Online (Sandbox Code Playgroud)
我可以得到一个范围fullRange吗?
上下文是我正在使用数据验证根据范围动态设置数据验证下拉列表。
示例:我有两个单元格-第一个单元格是具有类别列表的下拉列表,第二个单元格是具有子类别列表的下拉列表,这些子类别取决于在第一个单元格中选择的类别。
我实现此目标的方法基于类别选择,我根据该类别选择在隐藏行中填充了子类别列表。然后,我用于requireValueInRange设置该子类别单元格的数据验证。
它运行正常,但运行SUPER的速度较慢,但我正在尝试找出一种使速度更快的方法。我猜它缓慢的原因之一是因为我getRange在循环中使用以获得适当的requireValueInRange。所以我试图拉一个子范围,而不是每次都重新查询范围。
function setDataValidations() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var categoryRange = ss.getRange("A:A");
var subCatCells = ss.getRange("B:B");
var subCatRules = subCatCells.getDataValidations();
var rangeLength = categoryRange.getValues().length;
for (var i = 1; i < rangeLength; i++ ){
var catCell = categoryRange.getCell(i, 1);
var subCatOptions = ss.getRange("'subcats'!A" + i + ":P" + i);
var subCatRule = SpreadsheetApp.newDataValidation().requireValueInRange(subCatOptions, true).build();
}
catCells.setDataValidations(subCatRules);
}
Run Code Online (Sandbox Code Playgroud)
Range#getCell是一种Range从现有内引用a 的方式Range,因此您已经在执行要求的操作。您要注意的是,使用Range#setDataValidations优于逐个单元设置,因为它是批处理方法。鉴于您使用了requireValueInRange验证规则,因此无法避免获取其他Ranges。
但是,对于使用明确定义的关系的特定用例,可以通过使用RangeLists 来更有效地获取它们。A RangeList是批量获取的Range,通常用于对不相交范围进行同等对待的用途。
function setDVs() {
const wb = SpreadsheetApp.getActive();
const catSheetName = "the name of the sheet that has the dropdowns",
sheet = wb.getSheetByName(catSheetName),
maxDVs = sheet.getLastRow();
// Create the A1-notation or R1C1-notation Arrays identifying the ranges we need.
const subCatNotations = [];
const subCatSheetName = "the name of the sheet that has the ranges with required values"
for (var r = 1; r <= maxDVs; ++r)
subCatNotations.push("A" + r + ":P" + r); // 1 row, cols A:P
// Range#setDataValidations requires an Array of Array of DataValidations.
// Thus, wrap the new rule in a new array if updating a single column.
const new_dvs = wb.getSheetByName(subCatSheetName)
.getRangeList(subCatNotations).getRanges()
.map(function (subCatRange) {
return [
SpreadsheetApp.newDataValidation().requireValueInRange(subCatRange, true).build()
];
});
// Batch-apply the new rules to the `catSheetName` sheet.
if (new_dvs.length && new_dvs[0].length)
sheet.getRange(1, 1, new_dvs.length, new_dvs[0].length).setDataValidations(new_dvs); // col A
}
Run Code Online (Sandbox Code Playgroud)
参考文献
小智 5
下面的示例允许获取由所有行和仅某些列组成的子范围。
function getRangeByCols( myRange, fromCol, toCol){
firstRowIndex = myRange.getRow()
firstColIndex = myRange.getColumn()
rowsNumber = myRange.getHeight()
colsNumber = myRange.getWidth()
return myRange.getSheet().getRange(firstRowIndex,firstColIndex+fromCol-1,rowsNumber,toCol-fromCol+1)
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2101 次 |
| 最近记录: |