I will begin by saying that I am incredibly inexperienced with coding, so any help would be greatly appreciated!
I am trying to show/hide rows based on whether a checkbox is ticked or not. For example, I have a checkbox in A5 - If it is unchecked, I want it to hide rows 6:18, and if it is checked, I want it to show rows 6:18.
The same goes for a checkbox in A19, to hide/show rows 20:26 respectively. A27 for rows 28:37 etc.
I have found a previous forum post, in which I will link the code below, however the first checkbox is hiding ALL rows (Eg. if A5 is unchecked, it is hiding rows 6:18, 20:26 AND 28:37. When it is then checked, it is only showing rows 6:18.
function onEdit(e) {
var cfg = { // Please set this object.
A5: {startRow: 6, endRow: 18},
A19: {startRow: 20, endRow: 26},
A27: {startRow: 28, endRow: 37},
};
var activeRange = e.range.getA1Notation();
var ranges = Object.keys(cfg);
if (cfg[activeRange]) {
var sheet = e.source.getActiveSheet();
var values = sheet.getRange(ranges[0] + ":" + ranges[ranges.length - 1]).getValues();
values.forEach(function(e, i) {
if (e[0]) {
sheet.showRows(cfg[ranges[i]].startRow, cfg[ranges[i]].endRow - cfg[ranges[i]].startRow);
} else {
sheet.hideRows(cfg[ranges[i]].startRow, cfg[ranges[i]].endRow - cfg[ranges[i]].startRow);
}
});
}
}
As discussed, the first checkbox is hiding ALL rows (Eg. if A5 is unchecked, it is hiding rows 6:18, 20:26 AND 28:37. When it is then checked, it is only showing rows 6:18.
If my understanding is correct, how about this modification? Please think of this as just one of several answers.
var values = sheet.getRange(ranges[0] + ":" + ranges[ranges.length - 1]).getValues();
values.forEach(function(e, i) {
if (e[0]) {
var values = sheet.getRange(ranges[0] + ":" + ranges[ranges.length - 1]).getValues().filter(String); // Modified
values.forEach(function(e, i) {
if (e[0] === true) { // Modified
If I misunderstood your question and this was not the result you want, I apologize.
Tanaike code did not work for me if the rows were not empty. This worked for me:
function onEdit(e) { var cfg = { // Please set this object. A5: {startRow: 6, endRow: 18}, A19: {startRow: 20, endRow: 26}, A27: {startRow: 28, endRow: 37}, }; var activeRange = e.range.getA1Notation(); var sheet = e.source.getActiveSheet(); var ranges = Object.keys(cfg); var cells = [] for(var j = 0; j < ranges.length; j++){ cells.push(sheet.getRange(ranges[j])) } if (cfg[activeRange]) { cells.forEach(function(cell, i) { if (cell.getValue()) { sheet.showRows(cfg[ranges[i]].startRow, cfg[ranges[i]].endRow - cfg[ranges[i]].startRow); } else { sheet.hideRows(cfg[ranges[i]].startRow, cfg[ranges[i]].endRow - cfg[ranges[i]].startRow); } }); } }
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.