What could be causing the additional iteration in my for loop and preventing it from copying to the intended cells?

Every time I execute my script, it seems to run one additional time than necessary. For instance, it generates a PDF and marks a cell as processed below the last row.

Another issue is that the URLs do not align correctly with their corresponding names.

I understand that the code is messy, but I am willing to explain any part if it does not make sense.

Thank you in advance for any assistance!

You can access the spreadsheet here.

The code that is causing issues:

var ss = SpreadsheetApp.getActiveSpreadsheet()
var rawData = "rawData"
var practicePivot = "practicePivot"
var querySheet = "querySheet"
var pdfSheet = "pdfSheet"
var contactList = "contactList"

function createPDF(){

var sourceSheet = ss.getSheetByName("querySheet")
var pdfList = ss.getSheetByName("practicePivot")
var contactList = ss.getSheetByName("contactList")
var sourceRow = sourceSheet.getLastRow()
var sourceColumn = sourceSheet.getLastColumn()
var sourceStartRow = 4 //skips the headers and only pulls query data
var sourceStartColumn = 1
var sourceRange = sourceSheet.getRange(sourceStartRow, sourceStartColumn, sourceRow, sourceColumn)
var sourceValues = sourceRange.getValues()
var pdfLastRow = pdfList.getLastRow()
var storePracticeName = sourceSheet.getRange("A2").getValues()

var newSpreadsheet = SpreadsheetApp.create("Summary of Patients for" +storePracticeName)

sourceSheet.copyTo(newSpreadsheet, {contentsOnly: true})
newSpreadsheet.getSheetByName("sheet1").activate()
newSpreadsheet.deleteActiveSheet()

var pdfURLtemp = DriveApp.getFileById(newSpreadsheet.getId()).getAs("application/pdf")
var pdf = DriveApp.createFile(pdfURLtemp)
var pdfURL = pdf.getUrl()
Logger.log(pdfURL)
return pdfURL

}

function createQuery() 
{
//Duplication check
var pdfCreated = "pdfCreated";
var pdfEmailed = "pdfEmailed";

var sheet = ss.getSheetByName("practicePivot");
var startRow = 2; 
var lastRow = sheet.getLastRow();
var lastColumn = sheet.getLastColumn();

var dataRange = sheet.getRange(startRow, 1, lastRow, lastColumn)  ;
var data = dataRange.getValues();

for (var i = 0; i < data.length; ++i)
{
    var row = data[i];
    var practiceName = row[0]
    var pdfCheck = row[2]

    var copySelection = sheet.getRange(startRow + i, 1)
    var copyData = copySelection.getValues()
    var copyLocation = ss.getSheetByName("querySheet")
    var copyCell = copyLocation.getRange("A2")

    if (pdfCheck != pdfCreated)
    {
        var pdfURL = createPDF()
        copyCell.copyTo(copyData)
        sheet.getRange(startRow + i, 4).setValue(pdfURL)
        sheet.getRange(startRow + i, 3).setValue(pdfCreated)
        SpreadsheetApp.flush()
    }
}

}

Answer №1

The starting position should be row number 2:

let startRow = 2;

Your loop is currently looping until the last row count. If there are a total of 10 rows and data starts in row 2, then the loop should run only 9 times instead of 10.

Therefore, you need to adjust the stop condition for the loop:

let rowCount = data.length - 1; // Number of rows in the data (excluding the sheet)
for (let i = 0; i < rowCount; ++i)

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

Struggling to capture a "moment in time" of a form without losing any of the data

My form is highly dynamic, with interacting top-level elements triggering a complete transformation of the lower-level elements. I needed a method to maintain state so that if users partially entered data in one category, switched temporarily to another, a ...

Even after dynamically removing the class from the element, the Click event can still be detected

My buttons have a design like this: <a class="h-modal-btn branch-modal-btn"> Buy Now </a> The issue arises when I need to remove certain classes and add attributes to these buttons based on the query string in the URL. Skipping ahead ...

To restore the position of the chosen object in Three.js after clicking reset

I am facing an issue with resetting the position of my latest Object in three.js. Initially, my code consists of the following: function onDocumentMouseDown( event ) { event.preventDefault(); var vector = new THREE.Vector3( mouse ...

What is the best method to determine the currency associated with the code in dinero.js?

Is there an easy way to locate the dinero currency in the dinero.js/currencies package using its code? For example, a function called getCurrency that accepts a string as input and outputs the corresponding dinero currency. ...

"Adjusting the height of a div element while considering the

I have 2 elements with different heights and I want to make them equal: var highestEl = $('#secondElement').height(); $('.element').first().height(highestEl); I understand that the second element is always taller than the first one. W ...

Facing an infinite loop issue with my ng-view and the index.html page in AngularJS

Hello everyone, I have a question regarding AngularJS ngview. I just started learning about Angular a week ago. In my code, the webpage is showing an infinite loop of the index itself instead of displaying the correct page. I've searched on Stack Ove ...

Modify the state's value by updating it when your information is stored in an array

I am currently working with contact numbers stored in an array and utilizing native-base for data viewing. this.state = { leadProfile: { contactNumber: [ { "lead_contact_number": "0912 312 412312", "lead_contact_nu ...

Dynamically insert <td> elements into <tr> element using both jQuery and JavaScript

I am facing an issue with adding a new table data (td) element dynamically to the first table row (tr) in my JavaScript code. Here is the original table before adding the new td element: <table> <tbody> <tr> <t ...

Getting a boolean response from an asynchronous SQLite query in Express

I am currently developing a middleware that verifies the validity of a session (meaning it has a logged-in user attached). For this purpose, I am utilizing sqlite3 for node.js. Since I am not very familiar with JavaScript, I am facing some challenges figu ...

Retrieve data quickly and navigate directly to specified div element on page

I am facing an issue with scrolling on my website. While it currently works fine, I would like to make the scrolling instant without any animation. I want the page to refresh and remain in the same position as before, without automatically scrolling to a s ...

Restrict the occurrence of a specific element in the array to a maximum of X times

Functionality: A feature in this program will randomly display elements from an array. Each element can only be shown a certain number of times. Issue: I am unsure how to limit the number of times each element in the array is displayed. Currently, all ...

What could be causing WidgEditor, the JavaScript text editor, to fail to submit any values?

After clicking submit and attempting to retrieve text from the textarea, I am encountering a problem where the text appears blank. The reason for this issue eludes me. function textSubmit() { var text = $("#noise").val(); console.log(text); consol ...

Can the pointerover event be managed on a container within the am5 library?

While attempting to add an HTML label to a map and trigger a pointerover event, I encountered issues. The objective was to change the HTML content upon hover. Despite trying to incorporate a tooltip, the hover event failed to work properly, and the tooltip ...

Is there a way to capture the stdout and stderr output from a WebAssembly module that has been generated using Emscripten in JavaScript?

In my C++ code snippet below: #include <iostream> int main() { std::cout << "Hello World!" << std::endl; return 0; } I compile the code using: emcc -s ENVIRONMENT=shell -s WASM=1 -s MODULARIZE=1 main.cpp -o main.js This c ...

Producing numerous results from a single input

How can I ensure that users input their address correctly, including street, number, entrance, floor, and apartment, into a single form field without missing any of the values? Additionally, how can I then extract each value (street, number, entrance, floo ...

Changing the index of an item in an array in React based on order number

Hey there, I'm a new Reactjs developer with a question. It might be simple, but I'm looking to learn the best practice or optimal way to change the index of a selected item in an array based on user input. Essentially, the user will provide a num ...

Customize the label of the model in AngularStrap's typeahead ng-options to display something

Utilizing AngularStrap typeahead for address suggestions, I am facing an issue where I want to set the selected address object as my ng-model, but doing so causes me to lose the ability to display just one property of the object as the label. Here is an e ...

Transitioning the Background Image is a common design technique

After spending hours trying to figure out how to make my background "jumbotron" change images smoothly with a transition, I am still stuck. I have tried both internal scripts and JavaScript, but nothing seems to work. Is there any way to achieve this witho ...

Unable to trigger dispatchEvent on an input element for the Tab key in Angular 5

In my pursuit of a solution to move from one input to another on the press of the Enter key, I came across various posts suggesting custom directives. However, I prefer a solution that works without having to implement a directive on every component. My a ...

The angular.copy() function cannot be used within angular brackets {{}}

Within my controller, I am utilizing the "as vm" syntax. To duplicate one data structure into a temporary one, I am employing angular.copy(). angular.copy(vm.data, vm.tempData = []) Yet, I have a desire to transfer this code to the template view so that ...