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

Forwarding to another page following an AJAX post request to a Django view

I've been struggling to get this basic piece of code to work properly, despite trying numerous resources. I can't seem to pinpoint where I'm going wrong. Essentially, I have a javascript function submitData() that is supposed to make an ajax ...

Enhancing jQuery functionality: Ensuring newly added elements are aware of existing functions

I need assistance with my HTML table. Each row (tr) contains a value, for example 200$, and a delete button. How can I ensure that each new row added automatically knows the recent functions without having to call them every time? $(function () { $(&ap ...

Issues are arising with Jquery Scripts when running through Selenium in IE 9, resulting in the error message SCRIPT5009: '$' is undefined. However, these scripts are functioning correctly when executed directly in the web browser

While using Selenium, the code below is causing issues as it is not functioning properly. An error SCRIPT5009: '$' is undefined is being thrown in IE 9. However, if the code is executed in a web browser console after removing the "\" sign, i ...

Utilizing the outcome of an AJAX call in JavaScript

I am facing an issue with a query that is returning 2 rows. Below is my PHP code snippet: $arr = array(); $stmt = $dbh_conn->prepare("SELECT id,name FROM mytable WHERE id <= 2"); $stmt->execute(); $result = $stmt->fetchAll(); /*Array ( ...

Issue with splitting an array and eliminating commas - angular/ReactJS

Console Error: Unhandled error during execution of mounted hook Uncaught (in promise) TypeError: Cannot read properties of undefined (reading 'split') It seems to work up until it comes across a group that has no data for continent. This looks ...

How can I accurately show the server time and timezone in JS/jQuery regardless of the user's location?

Apologies for bringing up another time and timezone question related to web development. Despite numerous resources available, I am still struggling to grasp the concept of converting time between PHP and JavaScript. Here is my scenario: I aim to retrieve ...

JavaScript code that triggers a function when the mouse is moved over a description box on a

As a beginner in the field of Computer Science, I recently embarked on a project to create a website for sharing science articles with students. The goal is to spark curiosity and interest in science through this platform. One key feature I wanted to inclu ...

Vue 3 has a known issue where scoped styles do not get applied correctly within the content of a <slot> element

Utilizing the Oruga and Storybook libraries for creating Vue 3 components. The code in the Vue file looks like this: <template> <o-radio v-bind="$props" v-model="model"> <slot /> </o-radio> </template ...

Angular 8 delivers an observable as a result following a series of asynchronous requests

I am working on a simple function that executes 3 asynchronous functions in sequence: fetchData() { this.fetchUsers('2') .pipe( flatMap((data: any) => { return this.fetchPosts(data.id); }), fl ...

Adjusting canvas height in Storybook - Component does not fit properly due to low canvas height

I had a component that I needed to add to Storybook. It was working fine, but the styling was slightly off. I managed to resolve this by adding inline styling with position: absolute. Here is how it looks now: const Template: any = (args: any): any => ( ...

JavaScript - Issue arises when evaluating the sine of complex numbers of large magnitudes

I have developed a unique sine calculator that can handle the evaluation of the sine of complex numbers by utilizing polar coordinates and computing part of the infinite series defining the sine function. The calculator performs smoothly when dealing wit ...

cdkDropList does not function properly when used with ng-template in a dynamic component list

Exploring the new Drag&Drop features introduced in Angular Material 7, I am dynamically generating components using ng-template. <div cdkDropList (cdkDropListDropped)="dropLocal($event)"> <ng-template #components></ng-templat ...

Div with sidebar that sticks

I am currently working on setting up a website with a sticky sidebar. If you would like to see the page, click this link: On a specific subpage of the site, I am attempting to make an image Validator sticky, but unfortunately, it's not functioning a ...

With vuejs, only one place can control the changing of v-model

Hello, I am currently working on integrating VueJS2 code with Laravel Blade. However, I have encountered an issue with the following VueJS2 code: new Vue({ el:'.add_item_to_price_menu', data:{ percentage:null, }, methods: ...

JavaScript does not display checkbox values

I am currently testing whether checkbox values appear on the client side. When I execute the code, the alert is not showing anything. I would greatly appreciate any assistance, thank you. <div> <label name="finishing"class=" ...

Linking Two HTML Components in Angular 4 with Identical Values

Recently, I've started working with Angular and encountered an issue. In a table row, the value item.md_id is bound like this: <tr *ngFor="let item of driverData"> <td class="align-right" id="md_id" [(ngModel)]="item.md_id" name="driverId ...

Are there any options available for customizing the animation settings on the UI-bootstrap's carousel feature?

If you're interested in seeing an example of the standard configuration, check out this link. It's surprising how scarce the documentation is for many of the features that the UIB team has developed... I'm curious if anyone here has experie ...

a guide on expanding a submenu in a shiny dashboard sidebar without using automated functions

I am facing a challenge in manually expanding a submenu within a sidebar on shiny dashboard. The function updateTabItems does not seem to work with nested menus, only with normal menus. For example, when I click on 'Switch tab', it switches the ...

What is the proper way to utilize "three.module.js"?

I am currently learning how to utilize modules and decided to start with a simple example. However, I encountered an issue where the script does not want to run. I must be missing something crucial, but I can't seem to figure out what it is. I have tr ...

Invoke a CoffeeScript function within a jQuery function

Two files are causing me trouble: one is written in plain jQuery, and the other is a Coffeescript The jQuery file looks like this: $(document).ready(function(){ checkPrice(); }); In comparison, the CoffeeScript file appears as follows: $ -> c ...