以下是我用于自动隐藏/取消隐藏Google表格中行组的脚本。
Col B包含下拉菜单,允许用户根据named ranges切换隐藏或取消隐藏行。但是,脚本有点滞后。这是sample spreadsheet,您可以自己查看。
我还没有找到比在Google Apps脚本中创建四个不同阵列更有效的方法......但是对于如何加快这个脚本的任何建议都将非常感激!
(注意:该脚本使用"来自电子表格"以及" On edit"触发器。)
function hideRows() {
var ss = SpreadsheetApp.getActive();
var sheet = ss.getSheetByName("Sheet");
//create array of spreadsheet's named ranges
var namedRanges = ss.getNamedRanges();
var named = [];
for (var i = 0; i < namedRanges.length; i++) {
named.push(namedRanges[i].getName());
}
var arrName = named.sort();
//create array of named range values
var value = [];
for (var i = 0; i < arrName.length; i++) {
value.push(ss.getRangeByName(arrName[i]).getValue());
}
//create array of named range row indexes
var index = [];
for (var i = 0; i < arrName.length; i++) {
index.push(ss.getRangeByName(arrName[i]).getRowIndex());
}
//create array of named range row numbers
var rows = [];
for (var i = 0; i < arrName.length; i++) {
rows.push(ss.getRangeByName(arrName[i]).getNumRows());
}
for (var i = 0; i < arrName.length; i++) {
//If a value in value is equal to "Collapsed" then hide the corresponding named range
if (value[i] == "Collapsed") {
sheet.hideRows(index[i+1],rows[i+1]);
}
//If a value in value is equal to "Expanded" then show the corresponding named range
else if (value[i] == "Expanded") {
sheet.showRows(index[i+1],rows[i+1]);
}
}
}
答案 0 :(得分:1)
我没有测试过这个。我重写了代码,并将三个循环合并为一个循环。可以更多地合并代码,具体取决于您是否需要进一步将数据用于其他内容。例如,您正在对范围名称进行排序。如果不是真的需要按顺序排列它们,那么代码可以进一步合并。
function HideRows() {
var arrName,i,index,L,named,namedRanges,
rngByName,rngNumRows,rngRowIndex,rngVal,rows,
sheet,ss,thisRng,thisRngName,value;
ss = SpreadsheetApp.getActive();
sheet = ss.getSheetByName("Sheet");
named = [];
value = [];
index = [];
rows = [];
//create array of spreadsheet's named ranges
namedRanges = ss.getNamedRanges();
L = namedRanges.length;
for (i = 0; i < L; i++) {
named.push(namedRanges[i].getName());
}
arrName = named.sort();
Logger.log(arrName);
//create array of named range values
L = named.length;
for (i = 0; i < L; i++) {
thisRngName = arrName[i];
thisRng = ss.getRangeByName(thisRngName);
rngVal = thisRng.getValue();
rngRowIndex = thisRng.getRowIndex();
rngNumRows = thisRng.getNumRows();
value.push(rngVal);
index.push(rngRowIndex);//create array of named range row indexes
rows.push(rngNumRows);//create array of named range row numbers
//If a value in arrValue is equal to "Collapsed" then hide the corresponding named range
if (rngVal == "Collapsed") {
sheet.hideRows(index[i+1],rows [i+1]);
}
//If a value in arrValue is equal to "Expanded" then show the corresponding named range
else if (rngVal == "Expanded") {
sheet.showRows(index[i+1],rows [i+1]);
}
}
}