I'm using the google script to manage the google admin. Below is the script to list all google users in the domain.
If I create conditional formatting directly on the sheet, the rules are deleted whenever the script is launched. That's why I'd like to include the conditional formatting within the script itself, but it's not working?.
Basically what I want are :
if the value of the columns 'is Super Admin?' or 'is Delegated Admin?' are TRUE, then I'd like the rows to be colored in bold red.
And I'm trying to find out how to convert the results of lastLoginTime and creationTime (which are in string ISO8601 to datevalue, I know how to do it using formula, but I don't know how to using the script)
I'd really appreciate it if anyone can guide me.
Many many thanks in advance.
function listAllUser() {
var sheet11 = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("SheetNAME");
var sheet11range = sheet11.getRange("I3:Q")
sheet11range.clear()
var data = [];// array to store values
data.push(['Last Name','First Name','Email','orgUnitPath', 'is Suspended?','is Super Admin?','is Delegated Admin?', 'LastLoginTime','Creation']);// store headers
var pageToken, page;
do {
page = AdminDirectory.Users.list({
domain: 'DomainNAME',
pageToken: pageToken,
});
var users = page.users;
if (users) {
for (var i = 0; i < users.length; i++) {
try{
var user = users[i];
data.push([user.name.familyName,user.name.givenName,user.primaryEmail,user.orgUnitPath, user.suspended,user.isAdmin,user.isDelegatedAdmin, user.lastLoginTime , user.creationTime ]);//store in an array of arrays (one for each row)}
}catch (e){}
}}
pageToken = page.nextPageToken;
} while (pageToken);
sheet11.getRange(2,9,data.length,data[0].length).setValues(data).setVerticalAlignment("middle").setWrap(true);
var t1 = sheet11.getRange("I1:P1").merge();
var t1bis = t1.setValue("List of all USERS");
var dated = sheet11.getRange("Q1")
dated.setValue("Last updated: " + Utilities.formatDate(new Date(),Session.getScriptTimeZone(),'dd-MM-yy hh:mm'));
var range = sheet11.getRange("I1:Q2");
range.setFontWeight("Bold").setFontColor("Blue").setHorizontalAlignment("center").setVerticalAlignment("middle").setBackground("#beedda").setWrap(true);
var isSuperAdm = sheet11.getRange("N3:N").getValue();
var isDelegatAdm = sheet11.getRange("O3:O").getValue();
if(isSuperAdm==true || isDelegatAdm==true){
range.setFontWeight('bold').setFontColor('red')
}
}
After looking around for some tutorials, I finally succeeded to have what I wanted, formating the cell :
when the lastLoginTime was before the specific date
when the value of 'is Super Admin?' and 'is Delegated Admin?' are true
function cellsFormatting(){
var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("SheetName");
var range1 = sheet.getRange("A1:Q2");
range1.setFontWeight("Bold").setFontColor("Blue").setHorizontalAlignment("center").setVerticalAlignment("middle").setBackground("#beedda").setWrap(true);
var range2 = sheet.getRange ("A3:Q");
range2.setVerticalAlignment('middle').setWrap(true);
}
function setRangeToRedBoldFont(cellRange){
var sheet = SpreadsheetApp.getActiveSheet();
var range = sheet.getRange(cellRange);
var rule = SpreadsheetApp.newConditionalFormatRule()
.whenTextEqualTo("TRUE")
.setFontColor("#FF0000")
.setBold(true)
.setRanges([range])
.build();
var rules = sheet.getConditionalFormatRules();
rules.push(rule);
sheet.setConditionalFormatRules(rules);
}
function setRangeToGrayItalicFont(cellRange){
var sheet = SpreadsheetApp.getActiveSheet();
var range = sheet.getRange(cellRange);
var rule = SpreadsheetApp.newConditionalFormatRule()
.whenFormulaSatisfied("=DATEVALUE(MID($P3;1;10)) + TIMEVALUE(MID($P3;12;8))<date(2018;8;31)")
.setFontColor("#A9A9A9")
.setItalic(true)
.setRanges([range])
.build();
var rules = sheet.getConditionalFormatRules();
rules.push(rule);
sheet.setConditionalFormatRules(rules);
}
function listAllUser() {
var sheet11 = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("SheetName");
var sheet11range = sheet11.getRange("I3:Q")
sheet11range.clear();
cellsFormatting();
var t1 = sheet11.getRange("I1:P1").merge();
var t1bis = t1.setValue("List of all USERS");
var dated = sheet11.getRange("Q1")
dated.setValue("Last updated: " + Utilities.formatDate(new Date(),Session.getScriptTimeZone(),'dd-MM-yy hh:mm')); //will input the date & time when the script was launched
var data = [];// array to store values
data.push(['Last Name','First Name','Email','orgUnitPath', 'is Suspended?','is Super Admin?','is Delegated Admin?', 'LastLoginTime','Creation']);// store headers
var pageToken, page;
do {
page = AdminDirectory.Users.list({
domain: 'DomainNAME',
pageToken: pageToken,
});
var users = page.users;
if (users) {
for (var i = 0; i < users.length; i++) {
try{
var user = users[i];
data.push([user.name.familyName,user.name.givenName,user.primaryEmail,user.orgUnitPath, user.suspended,user.isAdmin,user.isDelegatedAdmin, user.lastLoginTime , user.creationTime ]);//store in an array of arrays (one for each row)}
}catch (e){}
}}
pageToken = page.nextPageToken;
} while (pageToken);
sheet11.getRange(2,9,data.length,data[0].length).setValues(data);
var formatRange = "I3:Q";
setRangeToRedBoldFont(formatRange);
setRangeToGrayItalicFont (formatRange);
}
For the row color:
For user.isAdmin & user.isDelegatedAdmin
function colorLine() {
const ss=SpreadsheetApp.getActive();
const sh=ss.getSheetByName('SheetName');
const rg=sh.getRange(3,9,sh.getLastRow(),9);
const vs=rg.getValues();
vs.forEach((r,i)=>{
if(r[5]||r[6]) {
sh.getRange(i+3,1,1,sh.getLastColumn()).setFontWeight('bold').setFontColor('red');
}
});
}
Related
I have the script below where some cells are protected because they contain formula but I can script linked to buttons that when executed, it updates the cell values in these protected cells, this is fine if you are the sheet owner but if you are not you get a error saying 'You are editing protected cells....'
I have seen some solutions where the script has been deployed as a web app and then set so it always runs as the owner but can't get this working for my use case, I deployed and set as to always run as me but this only seems like half the solution?
My code is below:
//
// Save Data
function submitData() {
var SPREADSHEET_NAME = "Data";
var SEARCH_COL_IDX = 0;
var RETURN_COL_IDX = 0;
var ss = SpreadsheetApp.getActiveSpreadsheet();
var formSS = ss.getSheetByName("Tool"); //Form Sheet
var datasheet = ss.getSheetByName("Data"); //Data Sheet
var str = formSS.getRange("A10").getValue();
var values = ss.getSheetByName(SPREADSHEET_NAME).getDataRange().getValues();
for (var i = 0; i < values.length; i++) {
var row = values[i];
if (row[SEARCH_COL_IDX] != str ) {
//SpreadsheetApp.getUi().alert(' "Dmp #' + formSS.getRange("A4").getValue() + ' "');
// return row[RETURN_COL_IDX];
//} else {
//Input Values
var values1 = [[formSS.getRange("A10").getValue(),
formSS.getRange("B10").getValue(),
formSS.getRange("C10").getValue(),
formSS.getRange("D10").getValue(),
formSS.getRange("E10").getValue(),
formSS.getRange("F10").getValue(),
formSS.getRange("G10").getValue(),
formSS.getRange("H10").getValue(),
formSS.getRange("I10").getValue(),
formSS.getRange("J10").getValue(),
formSS.getRange("K10").getValue()]];
var values2 = [[formSS.getRange("A10").getValue(),
formSS.getRange("B10").getValue(),
formSS.getRange("C10").getValue(),
formSS.getRange("D10").getValue(),
formSS.getRange("E10").getValue(),
formSS.getRange("F10").getValue(),
formSS.getRange("G10").getValue(),
formSS.getRange("I10").getValue(),
formSS.getRange("J10").getValue(),
formSS.getRange("K10").getValue()]];
values2[0].forEach(function(val) {
if (val === "") {
throw new Error("Please fill in Project, Category, Subsystem, Description and Created By Fields.");
}
})
// Save New Data
datasheet.getRange(datasheet.getLastRow()+1, 1, 1, 11).setValues(values1);
SpreadsheetApp.getUi().alert(' New Record Created ');
formSS.getRange("D10").clearContent();
formSS.getRange("E10").clearContent();
formSS.getRange("F10").clearContent();
formSS.getRange("G10").clearContent();
formSS.getRange("H10").clearContent();
formSS.getRange("I10").clearContent();
formSS.getRange("J10").setValue(new Date())
return row[RETURN_COL_IDX];
}
}
}
//=========================================================
// Clear form
function clearCell() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var formSS = ss.getSheetByName("Tool"); //Form Sheet
formSS.getRange("D10").clearContent();
formSS.getRange("E10").clearContent();
formSS.getRange("F10").clearContent();
formSS.getRange("G10").clearContent();
formSS.getRange("I10").clearContent();
formSS.getRange("J10").setValue(new Date())
return true ;
}
//=====================================================================
var SPREADSHEET_NAME = "Data";
var SEARCH_COL_IDX = 0;
var RETURN_COL_IDX = 0;
function searchStr() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var formSS = ss.getSheetByName("Tool"); //Form Sheet
var str = formSS.getRange("F4").getValue();
var values = ss.getSheetByName(SPREADSHEET_NAME).getDataRange().getValues();
for (var i = 0; i < values.length; i++) {
var row = values[i];
if (row[SEARCH_COL_IDX] == str) {
formSS.getRange("A6").setValue(row[0]) ;
formSS.getRange("B6").setValue(row[1]);
formSS.getRange("C6").setValue(row[2]);
formSS.getRange("D6").setValue(row[3]);
formSS.getRange("E6").setValue(row[4]);
formSS.getRange("F6").setValue(row[5]);
formSS.getRange("G6").setValue(row[6]);
formSS.getRange("H6").setValue(row[7]);
formSS.getRange("I6").setValue(row[8]);
formSS.getRange("J6").setValue(row[9]);
return row[RETURN_COL_IDX];
}
}
}
//===================================================================
function rowDelete() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var formSS = ss.getSheetByName("Tool"); //Form Sheet
var datasheet = ss.getSheetByName("Data"); //Data Sheet
var ui = SpreadsheetApp.getUi();
var response = ui.alert(
'Are you sure you want to delete this record?',
ui.ButtonSet.YES_NO);
// Process the user's response.
if (response == ui.Button.YES) {
var str = formSS.getRange("F4").getValue();
var values = ss.getSheetByName(SPREADSHEET_NAME).getDataRange().getValues();
for (var i = 0; i < values.length; i++) {
var row = values[i];
if (row[SEARCH_COL_IDX] == str) {
var INT_R = i+1
datasheet.deleteRow(INT_R) ;
formSS.getRange("A6").clearContent();
formSS.getRange("B6").clearContent();
formSS.getRange("C6").clearContent();
formSS.getRange("D6").clearContent();
formSS.getRange("E6").clearContent();
formSS.getRange("F6").clearContent();
formSS.getRange("G6").clearContent();
formSS.getRange("H6").clearContent();
formSS.getRange("I6").clearContent();
formSS.getRange("J6").clearContent();
return row[RETURN_COL_IDX];
}
}
}
}
//====================================================================
function updateData() {
var SPREADSHEET_NAME = "Data";
var SEARCH_COL_IDX = 0;
var RETURN_COL_IDX = 0;
var ss = SpreadsheetApp.getActiveSpreadsheet();
var formSS = ss.getSheetByName("Tool"); //Form Sheet
var datasheet = ss.getSheetByName("Data"); //Data Sheet
var str = formSS.getRange("A6").getValue();
var values = ss.getSheetByName(SPREADSHEET_NAME).getDataRange().getValues();
for (var i = 0; i < values.length; i++) {
var row = values[i];
if (row[SEARCH_COL_IDX] == str) {
var INT_R = i+1
formSS.getRange("J6").setValue(new Date())
var values1 = [[formSS.getRange("A6").getValue(),
formSS.getRange("B6").getValue(),
formSS.getRange("C6").getValue(),
formSS.getRange("D6").getValue(),
formSS.getRange("E6").getValue(),
formSS.getRange("F6").getValue(),
formSS.getRange("G6").getValue(),
formSS.getRange("H6").getValue(),
formSS.getRange("I6").getValue(),
formSS.getRange("J6").getValue()]];
var values2 = [[formSS.getRange("A6").getValue(),
formSS.getRange("B6").getValue(),
formSS.getRange("C6").getValue(),
formSS.getRange("D6").getValue(),
formSS.getRange("E6").getValue(),
formSS.getRange("F6").getValue(),
formSS.getRange("G6").getValue(),
formSS.getRange("I6").getValue(),
formSS.getRange("J6").getValue()]];
values2[0].forEach(function(val) {
if (val === "") {
throw new Error("Please fill in Revisions, Project, Category, Subsystem, Description and Updated By Fields.");
}
})
datasheet.getRange(INT_R, 1, 1, 10).setValues(values1);
formSS.getRange("A6").clearContent();
formSS.getRange("B6").clearContent();
formSS.getRange("C6").clearContent();
formSS.getRange("D6").clearContent();
formSS.getRange("E6").clearContent();
formSS.getRange("F6").clearContent();
formSS.getRange("G6").clearContent();
formSS.getRange("H6").clearContent();
formSS.getRange("I6").clearContent();
formSS.getRange("J6").clearContent();
formSS.getRange("E4").clearContent();
SpreadsheetApp.getUi().alert(' Record Updated ');
return row[RETURN_COL_IDX];
}
}
}
There are several posts about this, I'll paste a response from one from yesterday. What I recommend specifically in your case is to run the script when there's an edit bye the user in a certain cell. For example a Tickbox, or a Drop-down menu (in a cell) that allows the user to select which function to run:
If you already have an onEdit function working, that's a simple trigger run by whoever is editing the sheet. Meaning that if you protect column A, it won't be editable by that simple trigger because the user won't have permissions
In order to work this out, I encourage you to protect your column as explained here, change your name function or extract in a new function the part about this specific code you're talking about; and set an installable trigger that runs on event. This way it'll be run as you used to but as it came from your own account. As you have permissions for editing ColA the timestamp will be set by the installable trigger but the other user won't be able to edit it since he/she doesn't have the permissions. Try it and let me know!
I'm need some assistance in my problem.
I'm currently working on a script that works like this :
Send form
Lookup the value in table
Get the row number to use in another function
I have searched for the solution but mostly use logger to display value, I need the value as local variable to be used in other function.
Here is my current code up until the point I try to get row number :
function autoFillGoogleDocFromForm(e) {
//e.values is an array of form values
var Timestamp = e.values[0];
var Nama = e.values[1];
var Prinsipal = e.values[2];
var Email = e.values[3];
var Site = e.values[4];
var Mobil = e.values[5];
var Jumlah = e.values[6];
var ETD = e.values[7];
var ETA = e.values[8];
var Keterangan = e.values[9];
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheetByName('Master Email Site');
var data = sheet.getDataRange().getValues();
var RowCabang = Site
for(var i = 0; i<data.length;i++){
if(data[i][0] == Site){ //[0] because column A
return i+1;
}
}
var EmailCol = 2;
var EmailDest = sheet.getRange(RowCabang, EmailCol).getValue();
With this script, the trigger is completed but it doesnt capture the row number as var to be used.
Thank you for your assistance.
Try this pattern:
let RowCabang;
data.some((row, index) => {
if (row[0] === Site) {
RowCabang = index + 1;
return true;
}
});
I'm trying to set a dynamic dropdown in Google Sheet using Apps Script. I managed to get most parts working except setting the data validation in the cells necessary:
function sheetByName(ssId, sheetName) {
var ss = SpreadsheetApp.openById(ssId);
var sheet = ss.getSheetByName(sheetName);
return sheet;
};
function columnByName(sheet, columnName) {
var data = sheet.getDataRange().getValues();
var column = data[0].indexOf(columnName);
return column;
};
function columnValues(sheet, index) {
var data = sheet.getDataRange().getValues();
var values = [];
for(n=1; n<data.length; ++n) {
values.push(data[n][index]);
}
return values;
}
function columnSetDataValidation(sheet, index, options) {
var data = sheet.getDataRange().getValues();
var rule = SpreadsheetApp.newDataValidation()
.requireValueInList(options)
.setAllowInvalid(true)
.build();
for(n=1; n<data.length; ++n) {
var cell = data[n][index];
};
};
function dropDownBedrijven() {
var sheetCollegas = sheetByName("<<ID HERE>>", "Collegas");
var sheetBedrijven = sheetByName("<<ID HERE>>", "Bedrijven");
var getColumnIndexInBedijven = columnByName(sheetBedrijven, "Bedrijf");
var getColumnIndexInCollegas = columnByName(sheetCollegas, "Bedrijf");
var bedrijven = columnValues(sheetBedrijven, getColumnIndexInBedijven).filter(item => item);
columnSetDataValidation(sheetCollegas, getColumnIndexInCollegas, bedrijven);
};
I can't manage to get the function columnSetDataValidation to set data validation in the required cells.
Do you have any idea how to go about it?
You need to use range.setDataValidation(rule) with a range.
In your function columnSetDataValidation you are correctly building the rule, but are failing to assign the rule to a range. You are looping over the values of the range and then changing the value of var cell until the loop ends. Nowhere did you call range.setDataValidation(rule).
Try the following solution:
function columnSetDataValidation(sheet, index, options) {
var range = sheet.getDataRange();
var rule = SpreadsheetApp.newDataValidation()
.requireValueInList(options)
.setAllowInvalid(true)
.build();
for(n = 1; n < range.getLastRow(); ++n) {
var cell = range.getCell(n,index);
cell.setDataValidation(rule);
};
};
References:
Range.getCell(row, column)
Range.setDataValidation(rule)
Try this:
function columnSetDataValidation() {
const ss=SpreadsheetApp.getActive();
const sheet=ss.getSheetByName('Sheet1');
const range = sheet.getRange(2,4,sheet.getLastRow()-1);//putting validation in column 4
const options=[1,2,3,4,5];
const rule = SpreadsheetApp.newDataValidation()
.requireValueInList(options)
.setAllowInvalid(true)
.build();
range.setDataValidation(rule);
}
Here are my 2 spreadsheets:
Gsheet1: Googlesheet for replication (only employee # and employee name would change)
Gsheet2: Config sheet (contains the employee #, employee name, replication status, pubHTML link) that would feed employee # and employee name on Gsheet1
So I have this code that have these functionalities below:
Replicate Gsheet1 depending on the number of employees (I currently have 800+ employees) on Gsheet2 and dump it to a google drive folder.
after replication, will set a "completed" replication status to Gsheet2.
Change the revision properties of the replicated sheet and make it published to web.
Get the link of the published web (pubhtml) and put it on Gsheet2 pubHTML link column.
What happens is when I try to logger.log the results of this code below assuming that I have 2 records on my Gsheet2, it loops three times, the first and third record in loop are the same.
var TemplatesFromDrive = DriveApp.getFolderById(SpreadsheetApp.getActive().getSheetByName("Master Config").getRange("B2").getValue()).getFiles();
while (TemplatesFromDrive.hasNext()) {
var File = TemplatesFromDrive.next();
Logger.log(File.getName());
I was thinking if it's because of the Spreadsheet.flush() that I'm missing. Where is the best place where I can put it on my code so my loop will work properly? Below is my full code.
function replicateCards() {
var ss = SpreadsheetApp.openById('Gsheet2-xxxx');
var copyCard = SpreadsheetApp.openById('Gsheet1-xxxx');
var getID = DriveApp.getFileById(copyCard.getId())
var card = copyCard.getSheetByName("Card");
var mastersheet = ss.getSheetByName("Mastersheet");
var employeeNumber2 = ss.getRange("A2:A").getValues;
var getLastRow = mastersheet.getLastRow();
var destinationFolder = DriveApp.getFolderById('googledrivefolder-xxx');
var changeColorToGrayList = card.getRangeList(['C7', 'E7', 'G7', 'I7', 'K7', 'M7', 'O7', 'Q7',
'C9', 'E9', 'G9', 'I9', 'K9', 'M9', 'O9', 'Q9',
'C11', 'E11', 'G11', 'I11', 'K11', 'M11', 'O11', 'Q11']);
var setValueToZero = card.getRangeList(['C8', 'E8', 'G8', 'I8', 'K8', 'M8', 'O8', 'Q8',
'C10', 'E10', 'G10', 'I10', 'K10', 'M10', 'O10', 'Q10',
'C12', 'E12', 'G12', 'I12', 'K12', 'M12', 'O12', 'Q12']);
for (i = 1; i < getLastRow; i++) {
var badgeStatus = mastersheet.getRange(i + 1, 5).getValue();
if (badgeStatus == "") {
var employeeNumber = mastersheet.getRange(i + 1, 1).getValue();
var employeeName = mastersheet.getRange(i + 1, 2).getValue();
copyCard.getRange("H3").setValue(employeeNumber);
copyCard.getRange("C3").setValue(employeeName);
SpreadsheetApp.flush();
getID.makeCopy(employeeNumber, destinationFolder);
mastersheet.getRange(1 + i, 5).setValue("completed");
SpreadsheetApp.flush();
var files = DriveApp.getFolderById(SpreadsheetApp.openById("Gsheet1-xxxx").getSheetByName("Config Sheet").getRange("B1").getValue()).getFiles();
while (files.hasNext()) {
var file = files.next();
Logger.log(file.getName());
var Found = false;
for (var j = 0; j < employeeNumber2.length; i++) {
if (employeeNumber2[j][0] == file.getName()) {
Found = true;
}
}
if (Found) {
continue;
}
try {
var fileId = file.getId();
var fileName = file.getName();
var revisions = Drive.Revisions.list(fileId);
var lastRevisionId = revisions.items[revisions.items.length - 1].id;
// get the resource and set the publish parameters
var resource = Drive.Revisions.get(fileId, lastRevisionId);
// Logger.log(resource);
resource.published = true;
resource.publishAuto = true;
resource.publishedOutsideDomain = true;
// publish to the web
Drive.Revisions.update(resource, fileId, lastRevisionId);
SpreadsheetApp.flush();
var openByID = SpreadsheetApp.openById(fileId);
SpreadsheetApp.flush();
var googleDriveSheet = openByID.getUrl().replace("edit", "pubhtml"); // or replace("edit", "pub");
SpreadsheetApp.flush();
mastersheet.getRange(1 + j, 9).setValue(googleDriveSheet);
SpreadsheetApp.flush();
} catch (err) {
Logger.log(err);
}
}
}
}
}
Change var getLastRow = mastersheet.getLastRow(); to var getLastRow = mastersheet.getLastRow()-1;
The reason why is because you've started to get your data from the
second row.
If you would start at the third, you should do var getLastRow = mastersheet.getLastRow()-2; ...
I'm trying to use this code in Script Editor to read the queries from Google Spreadsheet columns so that people who do not know Google Apps Scripts can use it when they want to change the queries like start-date, end-date, metrics, dimensions, etc...the codes can read start-date, end-date, metrics, dimensions, and filters successfully. However, I think it doesn't recognize the accountId, webPropertyId, and profileId from a sheet named "Report Configuration." I got an error "Response Code: 404. Message: Not Found". Could you help me on this? Below is the code I got from #Eudardo:
var LOG_SHEET_NAME = 'Unsampled Report Logs';
var ss = SpreadsheetApp.getActive();
var ui = SpreadsheetApp.getUi();
var sheet = ss.getSheetByName('Report Configuration');
var startDateRange = sheet.getRange(10,5);
var startDate = startDateRange.getValue();
var endDateRange = sheet.getRange(10,6);
var endDate = endDateRange.getValue();
var metricsRange = sheet.getRange(10,8);
var metrics = metricsRange.getValue();
var dimensionsRange = sheet.getRange(10,9);
var dimensions = dimensionsRange.getValue();
var filtersRange = sheet.getRange(10,11);
var filters = filtersRange.getValue();
function insertReport() {
var resource = {
'title': 'Medium Sale',
'start-date': startDate,
'end-date': endDate,
'metrics': metrics,
'dimensions': dimensions,
'filters': filters,
};
var ss = SpreadsheetApp.getActive();
var sheet = ss.getSheetByName('Report Configuration');
var accountId = sheet.getRange(10,18).getValue();
var webPropertyId = sheet.getRange(10,19).getValue();
var profileId = sheet.getRange(10,20).getValue();
try {
var request = Analytics.Management.UnsampledReports.insert(resource, accountId, webPropertyId, profileId);
} catch (error) {
ui.alert('Error Performing Unsampled Report Query', error.message, ui.ButtonSet.OK);
return;
}
var sheet = ss.getSheetByName(LOG_SHEET_NAME);
if (!sheet) {
sheet = ss.insertSheet(LOG_SHEET_NAME);
sheet.appendRow(['User', 'Account', 'Web Property', 'View', 'Title', 'Inserted Time', 'Updated Time', 'Status', 'Id', 'File']);
sheet.getRange(1, 1, 1, 10).setFontWeight('bold');
}
sheet.appendRow([
Session.getEffectiveUser().getEmail(),
request.accountId,
request.webPropertyId,
request.profileId,
request.title,
request.created,
request.updated,
request.status,
request.id
]);
}
// Scans LOG_SHEET_NAME and tries to update any report that is PENDING
function updateAllReports() {
var sheet = ss.getSheetByName(LOG_SHEET_NAME);
var lastRow = sheet.getLastRow();
var dataRange = sheet.getRange(2,1, lastRow, 10);
var data = dataRange.getValues();
for (var i=0; i<data.length; i++) {
// If data is PENDING let's try to update it's status. Hopefully it's complete now
// but it may take up to 24h to process an Unsampled Reprot
if (data[i][0] == Session.getEffectiveUser().getEmail() && data[i][7] == 'PENDING') {
try {
var request = Analytics.Management.UnsampledReports.get(data[i][1], data[i][2], data[i][3], data[i][8]);
} catch (error) {
ui.alert('Error Performing Unsampled Report Query', error.message, ui.ButtonSet.OK);
return;
}
data[i] = [
Session.getEffectiveUser().getEmail(),
request.accountId,
request.webPropertyId,
request.profileId,
request.title,
request.created,
request.updated,
request.status,
request.id,
request.status == 'COMPLETED' ? DriveApp.getFileById(request.driveDownloadDetails.documentId).getUrl() : ''
];
// If data is Complete let's import it into a new sheet
if (request.status == 'COMPLETED') {
importReportFromDrive(request.title, request.driveDownloadDetails.documentId);
}
}
}
// Write only once to the spreadsheet this is faster
dataRange.setValues(data);
}
function importReportFromDrive(title, fileId) {
var file = DriveApp.getFileById(fileId);
var csvString = file.getBlob().getDataAsString();
var data = Utilities.parseCsv(csvString);
// Find a suitable name for the new sheet
var i=1;
var sheetName = title;
while (ss.getSheetByName(sheetName)) {
sheetName = title + ' ('+ i++ +')';
}
var sheet = ss.insertSheet(sheetName);
var range = sheet.getRange(1, 1, data.length, data[0].length);
range.setValues(data);
}
Never mind. I just figured out why. It's because of my mis-use of getRange(). It's supposed to be getRange(row,column), but I referenced it as getRange(column,row). Silly me! :)