Apologies in advance if this has been asked already. With Mint shuttering and forcing us to Credit Karma, I’m hoping to build a semi-automated budget and spending tracker in Google Sheets, and would love if someone could help me figure out how to formulate a forEach loop script.
I have four columns in the range I want to loop through: Month, Expense, Amount, Category. I found a script that loops through the range (below). What I need help with is generating an if statement that will identify values in each row, and, if the conditions are met, add up the value in the Amount column for each met condition.
Ideally, the RETURN VALUES HERE line would execute something to the effect of: "if a row has April in the Month column and Groceries in the Category column, add the Amount cell from that row to the sum." Hopefully this makes sense. I’m new to scripting and appreciate any help on this I can get.
function logAprilGroceries() {
var range = SpreadsheetApp.getActive().getRangeByName("Statements");
var values = range.getValues();
values.forEach(function(row) {
row.forEach(function(col) {
RETURN VALUES HERE;
});
});
}
2
Answers
As recommended on https://developers.google.com/apps-script/guides/sheets, you should learn that Google Apps Script uses JavaScript as a programming language and that handling arrays is very common when working with Sheets.
I don’t think that you will need the inner loop (
row.forEach(function(col){...}
); instead, use array indices, i.e.,row[0]
for the first column,row[1]
for the second column and so on.Regarding the if statement, the syntax is
if(expression){...}
, where the expression might use comparison operators, i.e.,===
(equal),!==
(not equal).There are a lot of resources to learn the basics of JavaScript. I like the JavaScript course from FreeCodeCamp as, it’s free and it’s focused on "vanilla JavaScript", no APIs, HTML, and other stuff that is not used on Google Apps Script server-side scripts.
This function assumes it will be passed the ‘month’ and ‘category’ arguments. You could alternatively declare them as constants prior to the loop.