MCC Script: Account Spend (an intro to iterators)
Here’s another MCC level script that you can use to pull useful data and to improve/learn more coding.
If you haven’t used MCC level scripts before, this will introduce you to the concept of an ‘iterator’.
This loops through all accounts in your MCC, grabs the spend & then adds it to an array called accountData
Once all account’s have been finished, the data in the array is output to ‘Sheet1’ on your Sheet (as usual enter the sheet URL in the line at the top ‘let ss=’)
If your sheet doesn’t have a tab called ‘Sheet1’ you’ll get an error.
Iterators are very powerful, so take the time to walk through this code & learn - or ask chatGPT to explain what the code is doing if you like.
Happy coding!
// enter sheet url
var ss = '';
function main() {
var headers = ["Client ID", "Client Name", "Spend"];
var accountData = [headers];
var today = new Date();
var yesterday = new Date(today);
yesterday.setDate(today.getDate() - 1);
var firstDayOfMonth = new Date(today.getFullYear(), today.getMonth(), 1);
var startDate = Utilities.formatDate(firstDayOfMonth, "GMT", "yyyyMMdd");
var endDate = Utilities.formatDate(yesterday, "GMT", "yyyyMMdd");
var accountIterator = AdsManagerApp.accounts().get();
while (accountIterator.hasNext()) {
var account = accountIterator.next();
AdsManagerApp.select(account);
var spend = account.getStatsFor(startDate, endDate).getCost();
var row = [account.getCustomerId(), account.getName(), spend];
accountData.push(row);
}
var spreadsheet = SpreadsheetApp.openByUrl(ss).getSheetByName("Sheet1");
spreadsheet.clearContents();
spreadsheet.getRange(1, 1, accountData.length, accountData[0].length).setValues(accountData);
spreadsheet.getRange(1, 1, 1, accountData[0].length).setFontWeight("bold");
}