Skip to content

Instantly share code, notes, and snippets.

@sabotuer99
Created August 5, 2015 15:52
Show Gist options
  • Save sabotuer99/aad344d30c911c21416f to your computer and use it in GitHub Desktop.
Save sabotuer99/aad344d30c911c21416f to your computer and use it in GitHub Desktop.
Aggregates data from multiple Google sheets into a master sheet
function onOpen() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var searchMenuEntries = [{name: "Find Sheets", functionName: "search"},
{name: "Aggregate Data", functionName: "aggregate"}];
ss.addMenu("Aggregate", searchMenuEntries);
}
function search() {
// Get the active spreadsheet and the file list sheet
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheetByName("Sheets Being Aggregated");
// Set up the spreadsheet to display the results
var headers = [["File Name", "File Type", "URL", "ID"]];
sheet.clear();
sheet.getRange("A1:D1").setValues(headers);
// Search the files in the user's Docs List for the search term
var files = getSheets();
// Loop through the results and display the file name, file type, and URL
var i = 0;
while (files.hasNext()) {
i++;
var file = files.next();
sheet.getRange(i+2, 1, 1, 1).setValue(file.getName());
sheet.getRange(i+2, 2, 1, 1).setValue(file.getMimeType());
sheet.getRange(i+2, 3, 1, 1).setValue(file.getUrl());
sheet.getRange(i+2, 4, 1, 1).setValue(file.getId());
}
}
function aggregate(){
// Get the active spreadsheet and the file list sheet
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheetByName("Aggregated Data");
sheet.clearContents();
// Search the files in the user's Docs List for the search term
var files = getSheets();
// Loop through the results, get the data from each sheet
// and append to end of aggregated sheet
while (files.hasNext()) {
var file = files.next();
var key = file.getId();
var currentRow = sheet.getLastRow() + 1;
var formula = 'FILTER(IMPORTRANGE("' + key + '","sheet1!A:C"), NOT(ISBLANK(IMPORTRANGE("' + key + '","sheet1!A:A"))))';
sheet.getRange(currentRow, 1, 1, 1).setFormula(formula);
}
sheet.getDataRange().copyValuesToRange(sheet, 1, 3, 1, sheet.getLastRow());
}
function getSheets() {
var searchTerm = "@Feed";
return DriveApp.searchFiles('mimeType = "application/vnd.google-apps.spreadsheet" and title contains "' + searchTerm + '"');
}
//var formula = 'QUERY(IMPORTRANGE("' + key + '","sheet1!A:C"), "SELECT Col1, Col2, Col3 WHERE Col1 <> ' + "''" + '")';
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment