Guide to accessing and updating data in various tabs within a Google spreadsheet

I have two tabs named TAB A and TAB B.

My goal is to iterate through TAB A and extract a set of values that I can then paste into TAB B.

However, I encountered an error message saying, "Cannot read property 1, etc"

function getValuesFromModal(form) {
  var IdeasCounter = 0;
  const IDEA = 10,
    PROD = 26,
    PROM = 20,
    CLIENT = 4,
    ORANGE = "#e69138",
    GREEN = "#6aa84f",
    RED = "#e06666";
  var rangeSource = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Records").getRange("A2:V").getValues();
  var rangeDest = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Board").getRange("A2:E");
  
  
  for (i in rangeSource) {
    if (rangeSource[i][0] == "Ideas" && (!isNaN(parseInt(rangeSource[i][17])))) {
      rangeDest[IdeasCounter][0].setValue("( " + rangeSource[i][2] + " )" + "\n" + rangeSource[i][3] + "\n\n" + "[ " + rangeSource[i][17] + " ]");
      switch (rangeSource[i][17]) {
        case rangeSource[i][17] < (IDEA - 2):
          rangeDest[IdeasCounter][0].setBackground(GREEN);
          break;
        case rangeSource[i][17] > (IDEA):
          rangeDest[IdeasCounter][0].setBackground(RED);
          break;
        case rangeSource[i][17] < (IDEA):
          rangeDest[IdeasCounter][0].setBackground(ORANGE);
          break;
      }
      IdeasCounter++;
    }

  }

}

Answer №1

Upon reviewing your script, I have identified several issues and made the necessary adjustments:

  • I renamed rangeSource to accurately reflect its purpose of retrieving values rather than the actual range itself.
  • I introduced new arrays for storing destination values and cell backgrounds. This step ensures that existing values and background colors are not unintentionally overwritten when the script is executed. Additionally, iterating through an array of a range's values proves to be significantly faster than directly iterating through the range itself. Referencing best practices supports this optimization approach.

  • In place of the for..in loop you previously used, a sequential for loop is more appropriate in this context. Detailed rationale behind this recommendation can be found in this informative answer. Also, it's essential to note that looping through a Google Range object using the Array notation like [][] might result in performance degradation due to reliance on the slow getCell() method.

  • I isolated sourceValues[i][17] into a separate variable for clarity. Similarly, consider adopting this practice for other elements within sourceValues to enhance code readability and maintainability.

  • Your use of a switch statement for handling </> comparisons is incorrect. Alternatives to this misapplication with detailed explanations can be explored elsewhere; one such discussion can be accessed here.

  • To expedite processing speed, I leveraged batch operations for efficiently writing destination values and setting cell background colors. The usage of batch operations facilitates quicker execution compared to individual value assignments and background color configurations.

Subsequent to these modifications, the revised script appears as follows:

function getValuesFromModal(form) {
  var IdeasCounter = 0;
  const IDEA = 10,
    PROD = 26,
    PROM = 20,
    CLIENT = 4,
    ORANGE = "#e69138",
    GREEN = "#6aa84f",
    RED = "#e06666";
  var sourceValues = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Records").getRange("A2:V").getValues();
  var destRange = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Board").getRange("A2:A"); // Focus on column A exclusively
  var destNewValues = destRange.getValues();
  var destBackgrounds = destRange.getBackgrounds();
  for (var i=0; i<sourceValues.length; i++) {
    var ideaValue = sourceValues[i][17];
    if (sourceValues[i][0] == "Ideas" && (!isNaN(parseInt(ideaValue)))) {
      var destValue = "( " + sourceValues[i][2] + " )\n" + sourceValues[i][3] + "\n\n[ " + ideaValue + " ]";
      destNewValues[i][0] = destValue;
      if (ideaValue < (IDEA - 2)) { // Excluding ideaValue == 10 currently
        destBackgrounds[i] = [GREEN];
      } else if (ideaValue > IDEA) {
        destBackgrounds[i] = [RED];
      } else if (ideaValue < IDEA) {
        destBackgrounds[i] = [ORANGE];
      }
    }
  }
  destRange.setValues(destNewValues).setBackgrounds(destBackgrounds);
}

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

Toggle element visibility upon clicking

<table id="selectsupp"> <tr> <td> <select id="category"> <option value="display" readonly="true">-Shop By Category-</option> <option value="all">All</option> <option val ...

The functionality of enabling and disabling dynamic behavior in AngularJs is not functioning as anticipated

As a newcomer to AngularJS, I may have some basic questions. I am currently working on implementing dynamic behavior for a button click event, but it's not functioning as expected. Could this be due to an issue with scope? Below is my HTML code: < ...

Error in Blinking Tooltip when Hovering Skill Bubble (React and d3)

I've encountered a frustrating issue with tooltips on my website - they just won't stop blinking when I hover over the skill bubbles. I tried fixing the tooltips at a certain location, but whenever there's a bubble in that spot and I hover o ...

When Select2 doesn't find a suitable option, the text "other" will be displayed

Is it possible to show a default option in select2 dropdown if the user's typed input does not match any available options? $("something").select2({ formatNoMatches: function(term) { //return a predefined search choice } }); I have searched ...

The format provided is not utilized by Datetimepicker

I've encountered an issue with the Date Time Picker provided by JQuery. Despite setting a specific format, it seems to be using its default date format which results in the following error appearing in the console: Uncaught TypeError: F.mask.replace i ...

I am encountering problems with images that are imported as module imports in a Vue.js project

Currently, I have stored all the default images for my Vue project in a designated folder. The path to this folder is web/images/defaults/<imageNames>.png. Instead of importing each image individually in my components, I wish to create a file that co ...

Adjust rankings based on the number of upvotes received by a project

I'm facing a challenge with ranking projects based on the number of votes they receive. No matter the vote count, the project always ends up getting ranked as 1. To address this issue, I developed a function to manage the rank count and a return hand ...

Trigger a warning pop-up if a selection has not been made in a dropdown menu using jQuery

I am attempting to display an alert popup when the user fails to select a value from the dropdown menu. Below is my HTML code: <div id="reminder" class="popup-layout"> ... ... </form> </div> In my JavaScript function page, I have tried ...

The retrieved item has not been linked to the React state

After successfully fetching data on an object, I am attempting to assign it to the state variable movie. However, when I log it to the console, it shows as undefined. import React, {useState, useEffect} from "react"; import Topbar from '../H ...

Distinguishing Between URLs for Google Maps JavaScript API

Can you explain the discrepancy between two Google API URLs? One is https://maps.google.com/maps/api/js?key={api_key}, which is currently not functioning and returns an error when attempting to use it on a map to display coordinates. The other is https:/ ...

Simplified React conditional rendering made easy

Currently, I am utilizing React 16 with Material-Ui components. In my root component, I have a requirement to load a tab and a view conditionally based on a property. Although I have managed to implement this functionality, the code appears quite messy a ...

Error message: Unable to locate local module in node.js subdirectory

Exploring the folder structure within my application https://i.stack.imgur.com/Pkxpg.png Referring to app_modules/bar and app_modules/foo as local modules Root Folder package.json "dependencies": { "body-parser": "~1.18.2", "cookie-parser": "~ ...

Trying to use 'cpa' before it is initialized will result in an error

I encountered the error stated above while using this particular route: router.put('/edit/:id', async (req, res) => { const cpa = await CPASchema.findById(req.params.id).then(() => { res.render('edit', { cpa:cpa }); cons ...

The click() function in jQuery executing only once inside a "for" loop

This is an example of my HTML code: <!DOCTYPE html> <head> <title>Chemist</title> <link href="stylesheet.css" rel="stylesheet"> </head> <body> <h2 id="money"></h2> <table border="1px ...

A guide to deactivating the Material UI Link API element

Previously, I relied on Material UI's Button component with a disable property that allowed the button to be disabled based on a boolean value. However, I now want to use the Material UI Link component, which resembles a text link but functions like a ...

I'm searching for a universal guidebook on creating web page layouts

After 5 years of creating webpages, I have realized that my sites tend to have a nostalgic 1995 internet vibe. Despite being a C# programmer with knowledge in HTML, JavaScript, and CSS, my design skills could use some improvement. Is there a quick referenc ...

Unable to loop through the "dataList" retrieved from a service call to the java backend within an Angular 9 application

After receiving JSON data from a Java backend service called houseguidelines, the information is sent to an Angular application via a service call. I am attempting to iterate over this returned JSON data and add it to an array I have created. Unfortunately ...

When using Google Maps Autocomplete, always make sure to input the full state name instead of just the state

Utilizing the Google Maps autocomplete API, we have enabled our customers to search for locations in the format of city, state, country. The functionality is effective overall, but a recurring issue arises when searching for cities, such as 'Toronto&a ...

Encountered an issue with JSON serialization while using getServerSideProps in Next.js and TypeScript to retrieve products from the Stripe Payments API

Encountered Issue on Localhost Error: The error occurred while serializing .products returned from getServerSideProps in "/". Reason: JSON serialization cannot be performed on undefined. Please use null or exclude this value. Code Sample import ...

Fade in an image using Javascript when a specific value is reached

Here's the select option I'm working with: <div class="okreci_select"> <select onchange="changeImage(this)" id="selectid"> <option value="samsung">Samsung</option> <option value="apple">App ...