forked from benlcollins/introductionToAppsScript
-
Notifications
You must be signed in to change notification settings - Fork 0
/
017_IntroToAppsScript_addingFormulas.js
65 lines (41 loc) · 1.35 KB
/
017_IntroToAppsScript_addingFormulas.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
// add total for each row into our Sheet
function addRowTotals() {
const ss = SpreadsheetApp.getActive();
const sheet1 = ss.getSheetByName('Sheet1');
const lastRow = sheet1.getLastRow();
const data = sheet1.getRange(2,1,lastRow - 1,3).getValues();
console.log(data);
const totalsArray = [];
data.forEach(function(row) {
const name = row[0];
const cost = row[1];
const quantity = row[2];
const total = cost * quantity;
row.push(total);
totalsArray.push([total]);
console.log(row);
});
console.log(totalsArray);
// paste data back into Sheet
sheet1.getRange(2,4,lastRow - 1,1).setValues(totalsArray);
}
// add menu
// onOpen is a special function
// runs when your Sheet opens
function onOpen() {
const ui = SpreadsheetApp.getUi();
ui.createMenu('Custom Menu')
.addItem('Add Row Totals','addRowTotals')
.addItem('Add Grand Total','grandTotal')
.addToUi();
}
// add grand total function
function grandTotal() {
const ss = SpreadsheetApp.getActiveSpreadsheet();
const sheet1 = ss.getSheetByName('Sheet1');
const lastRow = sheet1.getLastRow();
const lastColumn = sheet1.getLastColumn();
// add total row
sheet1.getRange(lastRow + 1,1).setValue('TOTAL');
sheet1.getRange(lastRow + 1, lastColumn).setFormula('=SUM(D2:D' + lastRow + ')');
}