Reputation: 11
I am trying to write a script to fetch data from Google Analytics. I wrote this using help from lots of sites and youtube videos but unable to fix 1 issue in my code.
function myFunction() {
var app = SpreadsheetApp
var doc = app.getActiveSpreadsheet().getActiveSheet();
for(var i=0;i<107;i++){
var viewId = doc.getRange(i+2,1).getValue(); // Your Google Analytics view ID
var startDate = Utilities.formatDate(doc.getRange("K1").getValue(), "GMT+2", "yyyy-MM-dd");
var endDate = Utilities.formatDate(doc.getRange("K2").getValue(), "GMT+2", "yyyy-MM-dd");;
var metric = 'ga:sessions, ga:newUsers, ga:bounceRate';
var option = {'segment': 'gaid::reM9CWAgR0ys4_Ng4N_aVw'};
var result = Analytics.Data.Ga.get(viewId, startDate, endDate, metric, option); // Make the request
var sessions = result.totalsForAllResults['ga:sessions'];
var newusers = result.totalsForAllResults['ga:newUsers'];
var bouncerate = result.totalsForAllResults['ga:bounceRate'];
var doc = app.getActiveSpreadsheet(); // Current document
var sheet = doc.getActiveSheet(); // Current sheet
sheet.getRange(i+2,2,1,1).setValue(sessions); // Write total sessions
sheet.getRange(i+2,3,1,1).setValue(newusers); // Write toal newusers
sheet.getRange(i+2,4,1,1).setValue(bouncerate); // Write total bouncerate
}
}
Upvotes: 0
Views: 3048
Reputation: 11
This Got auto resolved once I changed the View ID in my sheet. I guess the problem was with view ID
Upvotes: 1
Reputation: 14179
The error occurs because the script does not find the startDate or endDate in K1 and/or K2 cell or because there are less then 107 view ids and by looping it finds an empty cell in the first column (or do not start from the second cell).
It doesn't depend on Google Analytics.
Upvotes: 0