Failure of app script to retrieve data from an external spreadsheet

In an attempt to consolidate data, this program aims to transfer information from one spreadsheet to another. The process involves retrieving all files within a designated folder (all of which are spreadsheets), extracting values from a specific range, and storing them in an array. Subsequently, the program switches to another spreadsheet where it attempts to populate the first row with the array values. Finally, once the data is transferred, the original file is moved to a different location.

var uploadG = DriveApp.getFolderById('')
var moveToG = DriveApp.getFolderById('')

function obtainAndImportData(uploadFolder){
  var internalFiles = uploadFolder.getFiles()
  while (internalFiles.hasNext()){
    var file = internalFiles.next()
    var fileID = file.getId()
    var copySheet = SpreadsheetApp.openById(fileID).getSheets()[0]

    var Cvals = copySheet.getRange("C1:C").getValues() 
    var lastToValue = Cvals.filter(String).length-2 

    var Csheet = pasteSheet.getRange("C1:C").getValues()
    var lastSheetToValue = Csheet.filter(String).length  

    var allRows = []
    for (i = 0;i = lastToValue;i++){
      allRows[i] = copySheet.getRange(`B${i+3}:P${i+3}`).getValues()
    }

    var rangeToUnify = pasteSheet.getRange(`B${lastSheetToValue+1}:P${lastSheetToValue + lastToValue + 1}`) 
    rangeToUnify.setValues(allRows)  

    file.moveto(moveToG)  
  }
}

Despite expectations, the execution of this program seems to remain incomplete. It fails to insert and move data without displaying any errors throughout the process.

Note: The program reads .xslx files, which are eventually converted to Google Spreadsheets upon upload to Google Drive. This conversion may be causing complications that are challenging to resolve.

Answer №1

Here is a modified version that aligns more closely with your original intention

function getAndImportData(uploadFolder) {
  var uploadG = DriveApp.getFolderById('')
  var moveToG = DriveApp.getFolderById('')
  var filesInFolder = uploadFolder.getFiles()
  while (filesInFolder.hasNext()) {
    var file = filesInFolder.next()
    var fileId = file.getId()
    var copySheet = SpreadsheetApp.getActive().getSheets()[0];
    var columnValues = copySheet.getRange("C1:C" + copySheet.getLastRow()).getValues()
    var rowLength = columnValues.length;
    var destSheet = pasteSheet.getRange("C1:C" + pasteSheet.getLastRow()).getValues()
    var lastValue = destSheet.length;
    var allRows = []
    for (i = 0; i < rowLength; i++) {
      allRows.push(copySheet.getRange(`B${i + 3}:P${i + 3}`).getValues()[0]);
    } 
    pasteSheet.getRange(lastValue + 1,2,allRows.length,allRows[0].length).setValues(allRows);
    file.moveto(moveToG) // moves file
  }
}

Answer №2

Areas for Improvement:

  • Upon reviewing your script, I noticed that in your for loop, you have used
    for (i = 0; i = lastToValue; i++) {
    . This will cause the loop to never finish.
    • I suspect that this might be the reason why your program doesn't complete its execution as expected and does not throw any errors.
    • To address this issue, it is necessary to update the loop to
      for (i = 0; i < lastToValue; i++) {
      . However, using allRows[i] = copySheet.getRange(B${i + 3}:P${i + 3}).getValues() within a loop can increase the processing cost. Reference
    • Similarly, using rangeToUnify.setValues(allRows) within a loop can also lead to high processing costs.
  • You are fetching values from the sheet using
    copySheet.getRange("C1:C").getValues()
    and
    pasteSheet.getRange("C1:C").getValues()
    . This approach retrieves all rows within the data range, resulting in increased processing costs.
  • Even after making the aforementioned modifications, there might be an error at rangeToUnify.setValues(allRows) due to a mismatch in the number of rows between the range and the values.
  • Lastly, the correct method should be file.moveTo(moveToG), instead of file.moveto(moveToG).

Consider implementing these changes into your script. Here's the modified version:

Modified Script:

Prior to running this script, ensure to set the variables for pasteSheet, uploadFolder, and moveToG.

function obtainAndImportData() {
  var pasteSheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("###"); // Provide the name of your "pasteSheet".
  var uploadFolder = DriveApp.getFolderById('###'); // Specify your folder ID.
  var moveToG = DriveApp.getFolderById('###'); // Define another folder ID.

  // Ref: https://stackoverflow.com/a/44563639
  Object.prototype.get1stNonEmptyRowFromBottom = function (columnNumber, offsetRow = 1) {
    const search = this.getRange(offsetRow, columnNumber, this.getMaxRows()).createTextFinder(".").useRegularExpression(true).findPrevious();
    return search ? search.getRow() : offsetRow;
  };

  var internalFiles = uploadFolder.getFilesByType(MimeType.GOOGLE_SHEETS);
  var values = [];
  while (internalFiles.hasNext()) {
    var file = internalFiles.next();
    var copySheet = SpreadsheetApp.open(file).getSheets()[0];
    var srcValues = copySheet.getRange("B3:P" + copySheet.get1stNonEmptyRowFromBottom(3)).getValues();
    values = [...values, ...srcValues];
    file.moveTo(moveToG);
  }
  pasteSheet.getRange(pasteSheet.get1stNonEmptyRowFromBottom(3) + 1, 2, values.length, values[0].length).setValues(values);
}
  • Executing this script fetches Spreadsheets from the "uploadFolder". Values are retrieved from "B3:P" of the first tab in each Sheet, then appended starting from column "B" of "pasteSheet".

Note:

  • In this revised version, the last row from the "C" column is fetched per your original script. If you wish to utilize the last row of the data range, consider using getLastRow().

References:

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

My tests are not passing because I included a compare method in the Array prototype. What steps can I take to fix this issue in either the

Embarking on the challenging Mars Rover Kata has presented a unique problem for me. My jasmine tests are failing because of my array compare method within the prototype. This method is crucial for detecting obstacles at specific grid points. For instance, ...

The WHATWG URL API allows creation of a new URL using the new URL

I've been experimenting with node and attempting to create an instance of the URL class to utilize its useful properties. Here's what I tried: const { URL } = require('url'); (...) http.createServer((request,response) => { let u ...

Express.js automatically sets timeouts for requests to static files

I've been facing this issue for several weeks now - after launching, Express functions properly for a few hours and then suddenly stops serving static files. The situation is as follows: GET / 304 153ms GET /js/bootstrap.min.js 200 120000ms GET /img/ ...

Issue encountered during production build in Angular 6 due to NGRX

Trying to create and test the production build, I used the following command: ng build --prod --configuration=production ng serve --prod --configuration=production The build process completed successfully, however, upon opening the site on browsers, an ...

The date displayed in moment.js remains static even after submitting a new transaction, as it continues to hold onto the previous date until

I am currently utilizing moment.js for date formatting and storing it in the database This is the schema code that I have implemented: const Schema = new mongoose.Schema({ transactionTime: { type: Date, default: moment().toDate(), ...

JavaScript error - Property value is not valid

When I use IE 6/7/8, I encounter a JavaScript error message. The problematic line of code reads as follows: document.getElementById('all').style.backgroundColor = color; The specific error reported in IE 6/7/8 is as follows: Invalid property ...

Extracting Parameters using JQuery's load Method

On a webpage, I am attempting to load a jsp page (another.jsp) within a div element while passing parameters. $("#div").load('another.jsp?a=1&b=2'); Despite trying various methods multiple times, I have not been able to get the desired outc ...

At what point should the term "function" be included in a ReactJS component?

As a beginner in ReactJS, I have been working through some tutorials and noticed that some code examples use the keyword function while others do not. This got me wondering what the difference is and when I should use each one. Render Example with functi ...

Is It Possible to Create Flash Content Without Using a SWF File?

Is there a way to embed Flash directly in HTML, rather than linking to an external SWF file? I am looking to send an HTML form via email for the recipient to fill out by opening it in a browser. The final step would involve copying the result to their clip ...

Issue with timestamp in the Instagram API call to retrieve media using AJAX (GET /media/search)

My API call is returning a 400 bad request error message: {"meta":{"error_type":"APIInvalidParametersError","code":400,"error_message":"invalid parameters-check the max\/min-timestamps, if you supplied them"}} Even though my request appears to be co ...

How can you use DOM manipulation to extract input data from an <input type="file"> element?

Is there a way to retrieve the data from an <input type="file"> element, specifically if it contains an image, without utilizing an html form? Here is the HTML code: <body> <input type= "file"> </body> ...

What steps can be taken to ensure express Node.JS replies to a request efficiently during periods of high workload

I am currently developing a Node.js web processor that takes approximately 1 minute to process. I make a POST request to my server and then retrieve the status using a GET request. Here is a simplified version of my code: // Setting up Express const app = ...

Utilize the href attribute on an image, whether it be through a class

I work as a designer and I'm looking to extract the same href link from class="kt-testimonial-title", either in id="slick-slide10", or in class="kt-testimonial-item-wrap kt-testimonial-item-0", or in class="kt-testimonial-image". Can this be achieved ...

How to activate a button only if the specified conditions are met using VueJS 3

I'm currently facing challenges while working on a form to enable a button when certain conditions are met. The form I created includes fields for name, phone number, options, and a message. Once all requirements are filled, I aim to re-enable the di ...

React developers are struggling with parsing XML data with ReactDOM

While working on my React application, I encountered an issue with parsing an XML file. When I hard code the XML data in my file listener, I get the correct answer (2): const raw = `<?xml version="1.0" encoding="ISO-8859-1" ?> <?xml-stylesheet ...

bespoke theme background hue

I currently have material-ui@next installed and I am attempting to customize the background color of the theme. Here is what I have tried: const customizedTheme = createMuiTheme({ palette: createPalette({ type: 'light', primary: purple ...

creating a while loop in node.js

In C#, the following code would be used: double progress = 0; while (progress < 100) { var result = await PerformAsync(); progress = result.Progress; await Task.Delay(); } This concise piece of code spans just 7 lines. Now, how can we ...

Decoding user input parameters within a vue module

It seems like I am hitting a wall when it comes to finding solutions for this particular issue. Currently, I have a component that is supposed to retrieve data from a file and display it. My intention is to only pass the filename to the component so that ...

Top recommendation for utilizing $scope variables in Angular applications

Currently, I am working on a new project and I want to ensure that I am correctly utilizing $scope. After watching an informative video on best practices, Miško mentioned that manipulating $scope properties directly may not be the best approach. Typical ...

WordPress AJAX call results in a response code of zero

TL;DR: Unique - Go straight to code below for issue. You can view the demo I am working on by following this link. In my `functions.php` file, I first localize my script: function ajaxurl(){ wp_enqueue_script( 'product-selector', get_templ ...