-
Notifications
You must be signed in to change notification settings - Fork 10
/
Copy pathsource.js
79 lines (64 loc) · 2.59 KB
/
source.js
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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
function _getSpreadsheet(key) {
return key ? SpreadsheetApp.openById(key) : SpreadsheetApp.getActiveSpreadsheet();
}
function getBackgroundColor(rangeSpecification, key) {
var sheet = _getSpreadsheet(key);
return sheet.getRange(rangeSpecification).getBackground();
}
function getForegroundColor(rangeSpecification, key) {
var sheet = _getSpreadsheet(key);
return sheet.getRange(rangeSpecification).getFontColor();
}
function sumWhereBackgroundColorIs(color, rangeSpecification, key) {
var condition = function (cell) { return cell.getBackground().toLowerCase() == color.toLowerCase(); };
return sumByCondition(rangeSpecification, condition, key);
}
/**
* Sums all the values of cells with a given background color.
*
* @param {color}
* @param {rangeSpecification} rangeSpecification - the range to search against.
* @param {key} key (optional) - the key of a remote spreadsheet. If provided the
* range lookup will be done remotely.
* @return A sum of the cell values.
* @customfunction
*/
function sumWhereBackgroundColorIsNot(color, rangeSpecification, key) {
var condition = function (cell) {
return cell.getBackground().toLowerCase() != color.toLowerCase();
};
return sumByCondition(rangeSpecification, condition, key);
}
function sumWhereForegroundColorIs(color, rangeSpecification, key) {
var condition = function (cell) { return cell.getFontColor().toLowerCase() == color.toLowerCase(); };
return sumByCondition(rangeSpecification, condition, key);
}
function sumWhereForegroundColorIsNot(color, rangeSpecification, key) {
var condition = function (cell) { return cell.getFontColor().toLowerCase() != color.toLowerCase(); };
return sumByCondition(rangeSpecification, condition, key);
}
/**
* Sums all the values of cells in the given range that has a
* specific condition.
*
* @param {rangeSpecification} rangeSpecification - the range to search against.
* @param {condition} condition - a function that determines if the cell should be
* summed or not.
* @param {key} key (optional) - the key of a remote spreadsheet. If provided the
* range lookup will be done remotely.
* @return A sum of the cell values.
* @customfunction
*/
function sumByCondition(rangeSpecification, condition, key) {
var sheet = _getSpreadsheet(key);
var range = sheet.getRange(rangeSpecification);
var sum = 0;
for (var i = 1; i <= range.getNumRows(); i++) {
for (var j = 1; j <= range.getNumColumns(); j++) {
var cell = range.getCell(i, j);
if(condition(cell))
sum += parseFloat(cell.getValue() || 0);
}
}
return sum;
}