I want to create a script, which will be grouping all not empty rows. But, i have problem with checking getDepth or getRange when group doesn’t exist. I get “undefined” and i can’t create easy check like “if getDepth < 0 or “undefined”” because script stopping. Few years ago i created many scripts on VBA but this Apps Scripts a little bit hard for me, I’m newbie here) Can anyone help me?)
JavaScript
x
31
31
1
function Grouping() {
2
var i = 2;
3
var j = 1;
4
var count = 0;
5
let firstCellCount = 0;
6
var lastRow = SpreadsheetApp.getActiveSheet().getLastRow();
7
8
for (; i < lastRow + 1; i++) {
9
var curCell = SpreadsheetApp.getActiveSheet().getRange(i, 1).getValue();
10
var firstCell = SpreadsheetApp.getActiveSheet().getRange(i - 1, 1).getValue();
11
var lastCell = SpreadsheetApp.getActiveSheet().getRange(i + 1, 1).getValue();
12
13
let a = SpreadsheetApp.getActiveSpreadsheet().getSheets()[0].getRowGroup(i, 1).getDepth();
14
15
if (a < 1) {
16
17
if (curCell !== "" && firstCell == "") {
18
firstCellCount = i;
19
}
20
if (curCell !== "") {
21
count = count + 1;
22
}
23
if (curCell !== "" && lastCell == "") {
24
SpreadsheetApp.getActiveSheet().getRange(firstCellCount + 1, 1, count).activate().shiftRowGroupDepth(1);
25
count = 0;
26
firstCellCount = 0;
27
}
28
}
29
}
30
}
31
Advertisement
Answer
It’s not clear how are you getting "undefined"
, anyway, Sheet.getRowGroup()
throws an exception if the group doesn’t exist:
JavaScript
1
4
1
h:mm:ss AM/PM Error
2
Exception: A row group does not exist with index 1 and group depth 1
3
myFunction @ Code.gs:2
4
Considering the above you might use try..catch
JavaScript
1
8
1
try{
2
const group = SpreadsheetApp.getActiveSpreadsheet().getSheets()[0].getRowGroup(i, 1);
3
// add here whatever you want to do with the group
4
} catch(error){
5
// add here something that you want to do when a exception occurs
6
}
7
// add here something that you want to do after handling the group that doesn't need a group
8
Resources