Error: Attempting to access property '7' of an undefined value

I am currently working on a code that checks if the checkboxes for CEO_box and Acc_box are checked. If they are, an email is sent to the corresponding email address in the column, and the inform_cell is set as 'informed'. However, I keep encountering an error that seems to be related to the var courseCol = data[i][7] line, but I can't identify any issues with it.

function sendEmailver2() {
  try{

    const sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("sheet1")
    var lr = sheet.getLastRow();
    var data = sheet.getDataRange().getValues();
   
    //msg body sheet
    const templateText = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("template").getRange(1,1).getValue();


    for(var i=2; i <= lr; i++) {
      var CEO_box = sheet.getRange(i, 25);
      var Acc_box = sheet.getRange(i, 26);
      var courseCol = data[i][7]
      var receiverName = data[i][6]
      var receiverEmail = data[i][18]
      var inform_cell = data[i][27]
      var totalAmount = data[i][12]


      if(Acc_box.isChecked() && CEO_box.isChecked() && inform_cell.getValue() =="uninformed") {
        var subject = "please check email"
        var messageBody = templateText.replace("{name}",receiverName).replace("{courseName}",courseCol).replace("{amountVal}", totalAmount)
        console.log("send Email to:"+ receiverEmail)
        MailApp.sendEmail(receiverEmail, subject, messageBody);
        inform_cell.setValue("informed");
        
      }


    }
  } catch(e) {
    SpreadsheetApp.getUi().alert(e)
  }

}

Answer №1

As previously mentioned, encountering error code 7 indicates a potential issue with

  var courseCol = data[i][7]

If the error message states "error reading properties of undefined," it likely means that data[i] is undefined at that point.

My assumption is that the problem lies within

for(var i=2; i <= lr; i++) {

You probably meant to use

for(var i=2; i < lr; i++) {

This discrepancy arises because getLastRow returns a sheet position starting from 1 in Google Sheets, while JavaScript arrays start counting from 0.

Therefore, [1,2,3] correspond to positions [1,2,3] in Excel/Google Sheets, but positions [0,1,2] in JS.

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

What is the best way to iterate through a JSON object using the stages array provided?

I am facing an issue with parsing the provided json to display the desired output on the screen. These are the steps I need to follow for parsing this json: 1. Extract the stages array from the json - for example, stages ["check_dependency_progress", "sh ...

Extract data from Markit On Demand API using JavaScript and AJAX

I'm struggling to properly parse the response from the API. While I can retrieve the entire response, I am a bit lost on how to effectively parse it. Below is my code snippet: <!DOCTYPE> <html> <head> <style> img ...

How to dynamically increase vote tallies with React.js

The voting system code below is functioning well, displaying results upon page load. However, I am facing an issue where each user's vote needs to be updated whenever the Get Vote Count button is clicked. In the backend, there is a PHP code snippet ...

Is it necessary to include extra headers when making an XmlHttpRequest POST?

When initiating an XmlHttpRequest POST connection var http = new XMLHttpRequest(); http.open("POST", url, true); Some suggest adding the following headers before sending the request: http.setRequestHeader("Content-type", "application/x-www-form-urlencod ...

Issue detected with XMLHttpRequest - "The requested resource does not have the 'Access-Control-Allow-Origin' header."

Currently, I am working on the frontend development of an application using Angular 2. My focus is on loading an image from a third-party site via XMLHttpRequest. The code I have implemented for this task is as follows: loadFile(fileUrl) { const ...

Unable to trigger button retrieved through ajax request

I am facing a minor issue with my php page. It returns a button using ajax, as you can see below: HTML snippet: <a href="#" class="unit_register_button"> Register </a> jQuery code: $('a.unit_register_button').click(function(e) ...

Deleting data while retaining it in a separate location by leveraging nodejs and

Is there a way to implement a soft delete in nodejs for MongoDB? If I have the following code, can it be modified to perform a soft delete instead or is there a different approach? Controllers/ category.js exports.remove = (req, res) => { const c ...

Two instances of the JavaScript confirm dialog appearing; Returning to previous page after clicking on an element

Newbie here, so please go easy on me. I need help with a confirmation message for the User. My JavaScript is supposed to trigger a Button click event when the User confirms, which will execute some back-end code. The back-end code then runs a JavaScript f ...

Express Concurrency: Managing Multiple Tasks Simultaneously

Looking to create an API using Express that is capable of processing requests either through multithreading or multiprocessing. For example, the following API has a 5-second sleep before responding. If I make 3 quick calls to it, the first response will ta ...

Top location for securely storing information in Angular 8

I have developed a web application using Angular 8. My goal is to secure routes and pages with dynamic access levels. For instance, I want to verify if a user has access to a specific route, and if not, redirect them to the login page. To do this, I cur ...

Display the duplicated values of an array extracted from a JSON object just once

Having some trouble creating a list from json data, you can check out the example. My goal is to display each value only once if duplicates occur (for example, if there are 2 Martini glasses, I only want one to appear in the list), while still preserving t ...

Troubleshooting: Issue with WCF service not processing POST requests

I encountered an issue when attempting to call a WCF service using AJAX from another project. The error message displayed was: The server encountered an error processing the request. The exception message is 'The incoming message has an unexpected me ...

What is causing the TypeError when trying to set a property on undefined in AngularJS?

I've taken on the challenge of building a microblog app to learn more about angularJS. One thing that's really getting me is trying to understand the differences between service, factory, and provider. After some research, I decided to go with s ...

Internal Server Error 500: Issue with Ajax/JavaScript

I have reviewed some previous posts, but unfortunately, they did not provide the help I need. When my program runs and I click on a button to trigger a JavaScript function, nothing happens - there is no response. In the Chrome debugger under the network ta ...

Retrieve various information from the MVC action method by making an AJAX request for two distinct button clicks

I am looking for a feature where clicking on the 'withPricing' button triggers an ajax call to retrieve the withPricing template from the action method, and clicking on the 'without pricing' button retrieves the withoutPricing template. ...

Is there a way to change the font size with a click in JavaScript or Angular?

Here is a breakdown of the 4 steps: 1.) Begin by clicking on a category 2.) The filtered products will be displayed 3.) Select the desired products from the filter 4.) Once selected, the products will appear in the rightmost part of the screen within t ...

Encountering this issue: Unable to access the property 'length' of an undefined variable

I'm currently developing an app using nuxt, vuetify 2, and typescript. Within the app, I have radio buttons (referred to as b1 and b2) and text fields (referred to as t1, t2, t3). When a user clicks on b1, it displays t1 and t3. On the other hand, w ...

Incorporating '@vite-pwa/nuxt' into a nuxt 3 project leads to hydration issues

I have a Nuxt 3 website that I want to make PWA enabled. To achieve this, I am utilizing '@vite-pwa/nuxt'. However, after adding the package and enabling PWA in my nuxt.config.ts file, I encountered two issues: Hydration errors occur when refre ...

A tutorial on how to create the appearance of disabled buttons that look the same as enabled buttons through the use

My button includes a text field that is constantly disabled. I would like for the text field to appear as bright as it does when the button is enabled. After disabling the button, they both appear dimmer compared to others and the text field follows suit ...

JavaScript functions do not work within the HTML code

I am currently working on my debut website and I'm facing an issue with the JavaScript file not functioning properly. Is there a chance you can help me troubleshoot this? I'm still in the learning stages of programming. This is the HTML content ...