Reputation: 1
I made a grade book with students names in column A , B for type of marks week 1 C,D,E,F week 2 G,H,I,J and so on till week 14
what I want is to hide all weeks except what am using by choosing from cell A1 the week that is shown this way I can show and hide columns dynamically.
this was the result:
function onEdit(e) {
var sheet = e.source.getActiveSheet();
var cell = e.range.getA1Notation();
if (cell === "A1") {
var cellValue = sheet.getRange(cell).getValue();
var numColumns = sheet.getMaxColumns();
for (var i = 1; i <= numColumns; i++) {
var headerValue = sheet.getRange(1, i).getValue();
if (headerValue === cellValue) {
sheet.showColumns(i);
} else {
sheet.hideColumns(i);
}
}
}
}
the problem is that it's very slow can someone help me make it faster please ?
Upvotes: 0
Views: 537
Reputation: 201428
getValue()
is used in the loop, the process cost becomes high.showColumns
can be moved out of the loop.sheet.getRange(cell)
can be modified to e.range
.When these points are reflected in your script, how about the following modification?
function onEdit(e) {
var { range, source } = e;
var { columnEnd, columnStart, rowEnd, rowStart } = range;
if (columnEnd == 1 && columnStart == 1 && rowEnd == 1 && rowStart == 1) { // This is "A1". // or if ([columnEnd, columnStart, rowEnd, rowStart].every(f => f == 1)) {
var sheet = source.getActiveSheet();
var cellValue = range.getValue();
var numColumns = sheet.getMaxColumns();
var headerValues = range.offset(0, 0, 1, numColumns).getValues()[0];
sheet.showColumns(1, numColumns);
headerValues.forEach((e, i) => {
if (e != cellValue) {
sheet.hideColumns(i + 1);
}
});
}
}
Upvotes: 0