Scriptlytics
  • Introduction
    • Welcome to the community
  • Account level scripts
    • Account overview (all time)
    • Account performance (date range)
    • Account performance (daily export)
    • Account performance (last 90 days)
    • Account search query optimizer
    • Account search query optimizer (yesterday)
    • Call asset scheduling
    • Account keyword optimizer (date range)
    • Account keyword optimizer (last 90 days)
    • Match type report (last 360 days)
    • Negative keyword list
  • Campaign level scripts
    • Campaign performance (date range)
    • Campaign performance (daily export)
    • Campaign performance (last 90 days)
    • Multiple campaign performance (last 90 days)
    • Ad groups (date range)
    • Ad groups (last 30 days)
    • Keyword optimizer (date range)
    • Keyword optimizer (last 30 days)
    • Impressions heatmap (date range)
    • Impressions heatmap (last 30 days)
    • Clicks heatmap (date range)
    • Clicks heatmap (last 30 days)
    • CTR heatmap (date range)
    • CTR heatmap (last 30 days)
    • Conversions heatmap (last 30 days)
    • Conversions heatmap (date range)
    • Conversion rate heatmap (last 30 days)
    • Conversion rate heatmap (date range)
    • CPC heatmap (last 30 days)
    • CPC heatmap (date range)
  • pmax scripts
    • Pmax segmentation
    • Pmax search query optimizer
    • Pmax search query optimizer (all time)
  • Call reports
    • Call report (date range)
    • Call report (evergreen)
  • Bulk edit and actions
    • Bulk upload template
    • Swap Base URL's
    • Copy campaign and swap base URL's
  • Alerts and notifications
    • Zero spend alert
  • MCC scripts
    • MCC account performance export
    • Revised MCC account performance export
  • Search ads
    • Keyword match optimizer
  • Google sheets
    • Remove the following keywords
    • Remove keywords that don't contain
    • Remove keywords that don't contain and create negative keyword list
  • Product title modification
Powered by GitBook
On this page
  1. MCC scripts

Revised MCC account performance export

This script fetches all accounts managed by the MCC (My Client Center) account and retrieves daily performance metrics for each account for the past 30 days. It stores the results in a specified Google Sheets document, creating a separate sheet for each account. Each sheet contains columns for Date, Impressions, Clicks, Cost, and Conversions. The script runs the data retrieval process for each account in parallel, improving efficiency. This organized structure allows for easy access and analysis of performance data across multiple accounts in one place.

To set up this script, follow these steps:

  1. Open your Google Ads account.

  2. Go to the "Tools & Settings" menu and select "Scripts".

  3. Click the "Create" or "+" button to create a new script.

  4. Copy and paste the following script.

function main() {
  // Spreadsheet where data will be written
  var spreadsheetId = 'INSERT-SPREADSHEET-ID';

  // Store the spreadsheet ID in the script properties
  PropertiesService.getScriptProperties().setProperty('SPREADSHEET_ID', spreadsheetId);

  // Get the list of accounts under the MCC
  var accountSelector = MccApp.accounts();

  accountSelector.executeInParallel('processClientAccount', 'finalize');

  Logger.log('Script finished running.');
}

function processClientAccount() {
  var spreadsheetId = PropertiesService.getScriptProperties().getProperty('SPREADSHEET_ID');
  var spreadsheet = SpreadsheetApp.openById(spreadsheetId);

  // Get the current account
  var account = AdsApp.currentAccount();
  var accountName = account.getName();
  var accountId = account.getCustomerId();

  // Create a sheet for the account if it doesn't exist, else clear existing sheet
  var sheet = spreadsheet.getSheetByName(accountName);
  if (!sheet) {
    sheet = spreadsheet.insertSheet(accountName);
  } else {
    // Clear all existing data
    sheet.clear();
  }

  // Set up headers
  sheet.appendRow(['Date', 'Impressions', 'Clicks', 'CTR', 'Conversions', 'Conversion Rate', 'Cost', 'Cost per click', 'Cost per conversion', 'ConversionValue', 'ConversionValue - Cost (Daily)', 'ConversionValue - Cost (Last 7 Days)', 'ConversionValue - Cost (Last 14 Days)', 'ConversionValue - Cost (Last 30 Days)']);

  // Function to fetch data for a specific duration
  function fetchData(duration) {
    var report = AdsApp.report(
      `SELECT Date, Impressions, Clicks, Cost, Conversions, ConversionValue
      FROM ACCOUNT_PERFORMANCE_REPORT
      DURING ${duration}`
    );
    return report.rows();
  }

  // Fetch data for the last 30 days
  var last30DaysRows = fetchData('LAST_30_DAYS');

  // Convert rows to arrays
  function convertRowsToArray(rows) {
    var data = [];
    while (rows.hasNext()) {
      var row = rows.next();
      data.push(row);
    }
    return data;
  }

  var last30DaysData = convertRowsToArray(last30DaysRows);

  // Create a map to store data by date
  var dataMap = {};
  for (var i = 0; i < last30DaysData.length; i++) {
    var row = last30DaysData[i];
    var date = row['Date'];
    dataMap[date] = {
      impressions: row['Impressions'],
      clicks: row['Clicks'],
      cost: row['Cost'],
      conversions: row['Conversions'],
      conversionValue: row['ConversionValue']
    };
  }

  // Write data to the sheet for columns A-J
  function writeData(sheet, dataMap) {
    for (var date in dataMap) {
      var data = dataMap[date];
      var impressions = data.impressions;
      var clicks = data.clicks;
      var cost = data.cost;
      var conversions = data.conversions;
      var conversionValue = data.conversionValue;

      // Calculate derived metrics (assuming clicks and impressions are not zero)
      var ctr = (clicks > 0) ? (clicks / impressions * 100).toFixed(2) + '%' : '0.00%';
      var conversionRate = (conversions > 0) ? (conversions / clicks * 100).toFixed(2) + '%' : '0.00%';
      var costPerClick = (clicks > 0) ? (cost / clicks).toFixed(2) : '$0.00';
      var costPerConversion = (conversions > 0) ? (cost / conversions).toFixed(2) : '$0.00';

      // Write data for columns A-J
      sheet.appendRow([
        date,
        impressions,
        clicks,
        ctr,
        conversions,
        conversionRate,
        cost,
        costPerClick,
        costPerConversion,
        conversionValue,
        '', '', '', '' // Placeholders for columns K-N
      ]);
    }
  }

  writeData(sheet, dataMap);

  // Calculate and write data for columns K-N
  function updateData(sheet, dataMap) {
    var lastRow = sheet.getLastRow();
    for (var i = 3; i <= lastRow; i++) {
      var date = sheet.getRange(i, 1).getValue();
      var conversionValueMinusCostDaily = calculateValueMinusCost(date, dataMap, 1);
      var conversionValueMinusCostLast7Days = calculateValueMinusCost(date, dataMap, 7);
      var conversionValueMinusCostLast14Days = calculateValueMinusCost(date, dataMap, 14);
      var conversionValueMinusCostLast30Days = calculateValueMinusCost(date, dataMap, 30);

      sheet.getRange(i, 11).setValue(conversionValueMinusCostDaily);
      sheet.getRange(i, 12).setValue(conversionValueMinusCostLast7Days);
      sheet.getRange(i, 13).setValue(conversionValueMinusCostLast14Days);
      sheet.getRange(i, 14).setValue(conversionValueMinusCostLast30Days);
    }
  }

  // Calculate ConversionValue - Cost for a given date and duration
  function calculateValueMinusCost(date, dataMap, days) {
    var targetDate = new Date(date);
    var totalConversionValue = 0;
    var totalCost = 0;
    for (var i = 0; i < days; i++) {
      var currentDate = new Date(targetDate);
      currentDate.setDate(targetDate.getDate() - i);
      var currentDateString = Utilities.formatDate(currentDate, AdsApp.currentAccount().getTimeZone(), 'yyyy-MM-dd');
      if (dataMap[currentDateString]) {
        totalConversionValue += parseFloat(dataMap[currentDateString].conversionValue);
        totalCost += parseFloat(dataMap[currentDateString].cost);
      }
    }
    return totalConversionValue - totalCost;
  }

  updateData(sheet, dataMap);

  // Insert a new row for totals
  sheet.insertRowAfter(1);

  // Set formulas for the total row
  var lastRow = sheet.getLastRow();
  sheet.getRange("B2").setFormula("=SUM(B3:B" + lastRow + ")");
  sheet.getRange("C2").setFormula("=SUM(C3:C" + lastRow + ")");
  sheet.getRange("D2").setFormula("=C2/B2");
  sheet.getRange("D2").setNumberFormat("0.00%"); // Format as percentage
  sheet.getRange("E2").setFormula("=SUM(E3:E" + lastRow + ")");
  sheet.getRange("F2").setFormula("=E2/C2");
  sheet.getRange("F2").setNumberFormat("0.00%"); // Format as percentage
  sheet.getRange("G2").setFormula("=SUM(G3:G" + lastRow + ")");
  sheet.getRange("H2").setFormula("=G2/C2");
  sheet.getRange("I2").setFormula("=G2/E2"); // Corrected formula
  sheet.getRange("I2").setNumberFormat("0.00%"); // Format as percentage
  sheet.getRange("J2").setFormula("=SUM(J3:J" + lastRow + ")");
  sheet.getRange("K2").setFormula("=SUM(K3:K" + lastRow + ")"); // ConversionValue - Cost (Daily)
  sheet.getRange("L2").setFormula("=SUM(L3:L" + lastRow + ")"); // ConversionValue - Cost (Last 7 Days)
  sheet.getRange("M2").setFormula("=SUM(M3:M" + lastRow + ")"); // ConversionValue - Cost (Last 14 Days)
  sheet.getRange("N2").setFormula("=SUM(N3:N" + lastRow + ")"); // ConversionValue - Cost (Last 30 Days)

  // Format cost and conversion value columns as currency
  var costColumn = sheet.getRange(2, 7, sheet.getLastRow() - 1, 1); // Column G (Cost)
  var cpcColumn = sheet.getRange(2, 8, sheet.getLastRow() - 1, 1); // Column H (Cost per click)
  var cpcvColumn = sheet.getRange(2, 9, sheet.getLastRow() - 1, 1); // Column I (Cost per conversion)
  var conversionValueColumn = sheet.getRange(2, 10, sheet.getLastRow() - 1, 1); // Column J (Conversion Value)

  costColumn.setNumberFormat("$0.00");
  cpcColumn.setNumberFormat("$0.00");
  cpcvColumn.setNumberFormat("$0.00");
  conversionValueColumn.setNumberFormat("$0.00");
}

function finalize(results) {
  Logger.log('Results: ' + results);
}








  1. Add the spreadsheet ID above.

  2. Save the script.

  3. Review and authorize the script to access your Google Ads and Google Sheets accounts.

  4. Run the script manually for the first time to populate the initial values in the spreadsheet.

  5. (Optional) Schedule the script to run on a specific cadence (ie: daily, weekly, monthly, etc.)

Note: Ensure that you have the necessary permissions to access and modify the target Google Spreadsheet.

PreviousMCC account performance exportNextKeyword match optimizer

Last updated 10 months ago