Scripting with Google Apps to consolidate multiple spreadsheets into a main document

I manage a small sales team (currently 5 members but growing) who input sales data into multiple sheets within one workbook. I am looking to automate the process by running a script to merge all these sheets on a daily basis.

Here is the breakdown of the daily stages:

1) Clear all existing records from the Master Daily sheet (to ensure any updates or changes are accounted for from individual sales sheets) 2) Iterate through each sheet and consolidate the data

There are 6 columns, all in the same order but with different data values.

View Demo Sheet Here

Edit Open until bounty awarded.

Code snippet attempt :

function merge() {
    var v, arr,
        ss = SpreadsheetApp.getActive();
    ss.getSheets().filter(function(s) {
        return s.getName()
            .indexOf('Project') > -1
    }).forEach(function(s, i) {
        v = s.getDataRange()
            .getValues()
            .filter(function(r) {
                return r.toString()
                    .length > 0
            })
        arr = (i == 0) ? v : arr.concat(v);
    })
    ss.getSheetByName('Master')
        .getRange(1, 1, arr.length, arr[0].length)
        .setValues(arr);
}

Any assistance would be greatly appreciated.

Thank you!

Answer №1

Here is a simplified version of your script:

//@OnlyCurrentDoc
function mergeData() {
  const spreadsheet = SpreadsheetApp.getActive();
  const data = spreadsheet
    .getSheets()
    .filter(sheet => !sheet.getName().includes('Master'))//excluding Master sheet
    .flatMap(sheet => sheet.getDataRange().getValues());//mapping sheets to values and flattening it
  spreadsheet.getSheetByName('Master')
    .getRange(1, 1, data.length, data[0].length)
    .setValues(data);
}

Updates Made:

  • Excluded the master sheet instead of including all project sheets
  • Optimized using v8 es6 syntax

Answer №2

Check out the SheetGo add-on for a quick and efficient way to complete tasks with just a few clicks.

Take a look at the following link:

Answer №3

The following sections outline the main functions:

dailysheets.gs:

function archiveDaily() {
  // Function to archive daily sheets
}

function createDailyTrigger() {
  // Function to create a daily trigger
}

These files serve as supportive assets for various projects.

triggers.gs:

//Filename: triggers.gs

// Functions to handle project triggers.
function deleteTrigger(triggerName){
  // Logic to delete specific trigger
}

function isTrigger(funcName){
  // Check if trigger exists for specified function
}

function deleteAllTriggers(){
  // Delete all project triggers
}

function displayProjectTriggers() {
  // Display all project triggers
}

globals.gs:

The 'Globals' sheet stores essential information and acts as a reference for other processes in the projects.

function getGlobals(){
  // Function to retrieve global variables
}

function setGlobals(dfltObj){
  // Function to set default global values
}

function getGlobal(name){
  // Get global value by name
}

function setGlobal(name,value){
  // Set global value by name
}

function cleanGlobals() {
  // Function to maintain the cleanliness of Globals sheet
}

Codes.gs:

This section includes a predefined menu setup.

function onOpen(){
  // Create custom menu on opening
}

function makeMenu(){
  // Generate custom menu
}

Examples of data sheets and images can be found in the provided links.

Answer №4

This script automates the process of archiving daily data from multiple tabs into a master tab in Google Sheets. Here's what it does:

1) Archives daily data regardless of naming conventions on other tabs, focusing only on correct naming for the master tab.

2) Skips header rows on other tabs assuming the master tab contains headers.

3) Triggers the script to run every day.

4) Includes a feature to archive the previous day's master data in case the script runs before accessing new data, storing only one day of archived data.

The EverydayTrigger function sets up the daily loop, while the MergeSheet function is responsible for merging the sheets. Detailed explanations are provided within the script itself for each line of code.

function EverydayTrigger() {
  ScriptApp.newTrigger("MergeSheets")
  .timeBased()
  .everyDays(1)
  .create();
}

function MergeSheets() {
  var app = SpreadsheetApp;
  var ss = app.getActiveSpreadsheet();
  var data = null;
  var RetrieveSheet = null;
  var PasteSheet = ss.getSheetByName("Master");

  /*
  // To use the archiving option
  var PrevArchSheetName = PasteSheet.getRange(1,1000).getValue();

  if(PrevArchSheetName.length > 1){
    var PrevArchSheet = ss.getSheetByName(PrevArchSheetName); 
    ss.deleteSheet(PrevArchSheet);
  }
  */

  var sheets = ss.getSheets();//get all sheets regardless of naming conventions

  /*
  // For archiving the previous day's data
  var ArchiveSheet = ss.insertSheet(new Date() + "Master");
  PasteSheet.getDataRange().copyTo(ArchiveSheet.getRange(1,1));
  PasteSheet.getRange(1,1000).setValue(ArchiveSheet.getName()); 
  */

  PasteSheet.getRange(2,1,PasteSheet.getLastRow(),PasteSheet.getLastColumn()).clear();//remove old information

  for (var i =0; i<sheets.length; i++){
    RetrieveSheet = ss.getSheetByName(sheets[i].getName());
    if (RetrieveSheet.getName() != 'Master'){
      // data = RetrieveSheet.getDataRange(); 
      data = RetrieveSheet.getRange(2,1,RetrieveSheet.getLastRow(),RetrieveSheet.getLastColumn()); 
      data.copyTo(PasteSheet.getRange(parseInt(PasteSheet.getLastRow())+1,1));
    }
  }
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

I'm attempting to store this HTML code in local storage in order to utilize it on a new cart page, but I keep encountering an error

Here is the HTML snippet: <div class="cofefe"> <img src="photos/Shop%20-%20French%2Roast.png"> <p>Somecoffee</p> <p>15</p> <p>French ...

I'm experiencing difficulty displaying my nested array in JavaScript

let array2 = ['Banana', ['Apples', ['Oranges'], 'Blueberries']]; document.write(array2[0][0]); In attempting to access the value Apples within this nested array, I encountered unexpected behavior. Initially, access ...

Information on the Manufacturer of Devices Using React Native

Struggling to locate the device manufacturer information. Using the react-native-device-info library produces the following output. There seems to be an issue with handling promises. I need to store the device manufacturer value in a variable. const g ...

Performing an Ajax GET request in jQuery with custom headers and displaying the response in a new tab/window

My AJAX GET request includes header parameters instead of URL parameters, like this: $.ajax({ url: "http://localhost/myendpoint/ABCDE-12345", headers: { 'X-Auth-Token' : myTokenId}, type: "GET", s ...

Invoke multiple stored functions using JavaScript, beginning with this one

One way to store and call a function later is by assigning it to a variable, like so: var storedFunction = functionName; //Later On storedFunction(); //Equivalent to functionName() If you want to store a function and also execute 'this' when ca ...

How to incorporate click and drag feature for rotating a 3D object using vue.js

Whenever I click a button, the rotation function is activated and allows me to rotate an object by hovering over it with my mouse. Now, I want to modify this behavior so that the object rotates only when I click on it and move the mouse (while holding dow ...

Jquery's ajax function is failing to execute the server side function

I have a specific structure for my solution: My goal is to execute the recommendationProcess function from CTL_RateRecommendationDetails.ascx.cs in CTL_RateRecommendationDetails.ascx Therefore, I wrote the following code: $.ajax({ type: "POST", ...

Issue with Bootstrap alert persisting even after being displayed once

Having trouble with alert messages in jQuery where I display the message, validate data, and then try to hide it again. No errors in the console, even when logging before and after the process. SOLUTION $('#password, #confirm_password').on(& ...

What steps should I take to modify the API addresses within the React project build?

In my React project, I am looking for a method to dynamically change the API addresses after building it. Is there a way to accomplish this without using environment variables? I want to be able to modify the API address even after the build process is c ...

Limit the frequency of rendering JSX elements in React by implementing debouncing techniques

Is there a way to delay the rendering of a jsx element in order to smooth out the animation? I have an expanding panel with content inside, and when the panel is empty, the animation works well. However, if the panel already contains content, the expansion ...

The React apexchart heatmap's height remains static despite attempting to change it through state updates

Seeking to dynamically resize the height of an "Apexcharts heatmap" based on server data. Despite attempting to manipulate code in various lifecycle methods, including componentDidMount() and where the data is received, I have not been successful. Within ...

Troubleshooting Node.js Application: Investigating Port Errors

After cloning a node.js application, I went through the setup process by running npm install and npm install -g nodemon. In order to run the application locally on port 3000, I added the following line in my app.js file: app.listen(3000, () => console. ...

Manually closing Bootstrap 4 Popper.js Tooltip on command

To activate a Bootstrap 4 Popper.js Tooltip using jQuery, I simply do the following: When the 'like' button is clicked, the tooltip will be displayed: $('.like-btn').on('click',function(){$(this).tooltip('show');}); ...

What is the best way to limit the containment property of the sortable feature to a specific div

The containment feature limits the dragging of elements to the edges of the browser window, causing scroll bars with excessive empty space. Inside a drop_down_list div, I have a list that needs to be sortable. To achieve this, I used the following code: ...

Cease the audio from playing unless you are actively hovering over the image

Is there a way to make the sound stop playing when you are not actively hovering over the picture? Any suggestions on how to achieve this would be greatly appreciated! imgarr[i].onmouseout=function(){ this.setAttribute('src',this.getAttribu ...

Sails encountering CORS preflight error due to cross-origin request

I am new to creating hybrid apps and have been following some tutorials. However, I encountered these errors on my browser console: Refused to load the script 'http://192.168.1.142:35729/livereload.js?snipver=1' due to Content Security Policy di ...

What is the best method for creating numerous Popovers within a single ID?

Is it possible to create multiple popovers with the same ID? <div class="card-text"> <a href="#" id="seelabel" data-toggle="popover" data-trigger="hover" title="Inkscape" data-content= ...

`Can you explain how to specify the elements of an array within a form using AngularJS?`

Below is an array containing objects: //Data source code $scope.data = [ { name: 'Lname', items: [{ label: 'Lastname', type: 'text', model: 'lname', pattern: '/^[a-zA-Z]$/', ...

obtain data from an array using Angular 5

i need assistance with retrieving values from an array. Below is my code snippet: this.RoleServiceService.getRoleById(this.id).subscribe(data => { this.roleData.push(data['data']); console.log(this.roleData); }) however, the resulting ar ...

Use jQuery to update the field without affecting the observable

Greetings to the wonderful stackoverflow community! I recently delved into using knockout just a few days back. Currently, I am utilizing it to create a dynamic menu builder for a CMS project that I'm deeply engrossed in. If you'd like to take ...