-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathSumAllCells.js
More file actions
47 lines (41 loc) · 1.08 KB
/
SumAllCells.js
File metadata and controls
47 lines (41 loc) · 1.08 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
/*
Created by: RemcoE33
https://github.com/RemcoE33/apps-script-codebase
*/
/**
* Return the sum of the same range on all your sheets.
*
* @param {"A1:D10"} range - Your range to sum.
* @param {"sheet1", "Sheet2"} [optional] exclude - Sheetnames to exclude inside an array.
* @return the sum of all the values
* @customfunction
*/
function SUM_ALL_CELLS(range, exclude) {
if (!Array.isArray(range)) {
range = [[range]]
};
const flatRange = range.flat();
const ss = SpreadsheetApp.getActiveSpreadsheet();
const sheet = ss.getActiveSheet().getName();
if(!exclude){
exclude = [sheet];
} else if(!Array.isArray(exclude)) {
exclude = [sheet, exclude];
} else {
exclude.push(sheet);
}
console.log(exclude);
const sheets = ss.getSheets();
let sum = 0;
sheets.forEach(s => {
if (!exclude.flat().includes(s.getName())) {
flatRange.forEach(range => {
s.getRange(range).getValues().flat().forEach(value => {
let number = (Number(value)) ? Number(value) : 0 ;
sum += number
});
});
};
});
return sum;
}