A custom script for Google Sheets that accesses data from cell "A" and populates cell "B" with information based on the value in cell "A"

Hey everyone,

I'm looking to create a script for Google Sheets that will check if there is a value in a cell within a row, and then populate another cell in the same row with a specific value. For instance, if a cell in row 2, column G contains anything other than empty quotes, I want to write "New issue" in the corresponding cell on row 2, column C. Here's what I have so far:

// Goal: Fill cells in Column G based on values in other cells in the same row

function formatSpreadsheet() {
  var sheet = SpreadsheetApp.getActive();
  var data = sheet.getRange("C3:1000").getValues();

  if (data !== "") {
    sheet.getRange("G3:G1000").setValue("New Issue");

  }
}

The issue with my current code is that it writes "New Issue" to all cells in the range G3-G1000 if any value is found in C3-C1000. What I actually need is for it to only update the corresponding row in column G when a value exists in the respective row of column C. So, if C4 has a value, G4 should be set to "New issue", and so on for each row.

Hopefully, this clarifies things, but feel free to ask me to provide more details. I'm unsure whether using IF statements or implementing a forEach loop would be more appropriate in this situation. I'm not very familiar with how to use forEach, unfortunately. Thanks a lot for your assistance!

Answer №1

To solve this request using Apps Script, we need to examine each element in the array and update the corresponding element in another range. To enhance efficiency, it is recommended to utilize batch operations like getValues() and setValues whenever feasible. Here is a potential solution:

function setNewIssueLabels() {
  const sourceRangeA1 = "C3:C1000", destStart = "G3";

  const sheet = SpreadsheetApp.getActive().getActiveSheet(),
        source = sheet.getRange(sourceRangeA1).getValues();
  if (!source.length || source[0].length !== 1)
    throw new Error("Expected single-column source range with at least 1 row");

  // Adding the original row index in the array.
  const inputs = source.map(function (row, index) {
    row.unshift(index);
    return row;
  })
  // Filtering out rows where the 2nd index (the original content) is an empty string.
  .filter(function (iRow) {
    return iRow[1] !== "";
  });

  var dest = sheet.getRange(destStart);
  if (dest.getNumRows() < source.length)
    dest = dest.offset(0, 0, source.length, 1)
  const outputs = dest.getValues();

  // Processing every row in 'inputs' (meaning every row in the source range that
  // has a value).
  inputs.forEach(function (iRow) {
    var originalIndex = iRow[0];
    // var originalContent = iRow[1];
    // var isActualNewIssue = outputs[originalIndex] === "";
    // if (isActualNewIssue) {
    outputs[originalIndex] = "New Issue";
    // } else {
    //   foo();
    // }
  });

  /**
   * Updating the destination range contents with the values from 'outputs',
   * which includes the previous values along with potentially new cells containing "new Issue"
   */
  dest.setValues(output);
}

I have included some logic, commented out for reference, to determine whether the value existed during the previous function call or is genuinely new.

Answer №2

It has been discovered that a straightforward equation can handle this task independently without the need for a script.

The formula "=ArrayFormula(if(len(C2:C),"New Issue",))" is sufficient to accomplish the goal.

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 take control of DOM alterations?

In the project I'm currently working on, the client has a modal box with its display property set to none. Upon clicking the CTA button, it triggers the application of the fadein and fadeout classes. This results in a change from display:none to displ ...

Focus on selecting each label within a table using JavaScript

In my current setup, I am attempting to customize radio buttons and checkboxes. Array.from(document.querySelectorAll("tr")).forEach((tr,index)=>{ var mark=document.createElement("span"); Array.from(tr.querySelectorAll("input")).forEach((inp,index ...

Ways to verify the order of the information within an array extracted from a file using JavaScript

After extracting marker data from a file containing USFM data at the provided USFM_file_link, I created an array featuring markers from each line: ['id','c','p','v','p','v','v','v& ...

Steps to solve React error message: "Warning: Every child in a list should have a distinct 'key' prop"

Currently, I am developing a React application that fetches movies and allows users to comment on them while also providing the option to vote/rate. Users can both comment and rate the movie they are viewing. Here is an excerpt from my code: <FormGrou ...

Ant Design radio group buttons are currently dysfunctional

I'm having some trouble with radio group buttons. Can anyone assist me with this issue? (your help is greatly appreciated) Current Problem: Radio Group buttons are unclickable. Not sure where the issue lies! Technologies Used: React hooks, styled-co ...

Tips for adding a CSS marker to the Videogular timeline at a designated time

My HTML player application allows users to search for a term and then displays the results along with the time when those words appear. By clicking on a specific sentence, the HTML player will start playing from that location. However, I would like to enha ...

Aframe Descend Rotation

I am currently working on a project in Aframe and I'm looking to implement a control/event that enables an entity to rotate downward. While attempting to create a new animation and add it as a child object to the entity, I have achieved successful re ...

List of random items:1. Red pen2

By using JavaScript, I want to generate a paragraph that contains a randomly ordered list of items (presented in paragraph format) for a basic website. The input would include: apples concrete a limited dose of contentment North Carolina The final ...

"Is there a JavaScript code snippet that can retrieve information from a JSON file

Is there a way to create a custom JavaScript function that can extract specific data from a JSON object based on certain keywords? I am working with a Task Manager API and would like to automatically populate fields based on the task title. Here is an exam ...

Is there a way to create a function that is able to return both a value and a promise

Assume I need to fetch a value only if an object is already present in my model. Otherwise, I should retrieve the output of an endpoint service: model.getDoohkyById = function( id ){ if( this.data ) { if( this.data.length > 0) { ...

Tips for consolidating multiple JavaScript files from various directories into one single file?

I am currently working on a project that involves multiple JavaScript files stored in various folders. My goal is to combine them all into a master.js file. The project structure looks like this: /dist/js/master.js <-- Output file /src/bootstrap-untou ...

sending parameters to package.json scripts

Currently, I am utilizing nodejs and in my package json file, I am required to define a test in the following manner: "test:mine": "cross-env NODE_ENV=test nyc mocha \"./tests/**/objectStore.test.ts\" ", When I execute npm run test, only that s ...

Interacting with dynamically created input fields using Jquery from a JSON loop

I'm stuck trying to figure out why this code isn't working for me. I'm attempting to retrieve the value of a textfield that was generated via a loop from a JSON file. At the end of this code, I've added a simple click(function() {alert ...

Obtaining verified user information through Express using a JWT token

Having recently ventured into Express, I have prior experience with Laravel and PHP. Currently, my concern lies with a database schema structured like this: Users table : created_by updated_by In Laravel, I could easily auto-fill the 'created_by&ap ...

Utilize express compression in Node.js to compress JSON data from the REST API endpoint

I recently developed a small RESTful application using Node.js. I attempted to compress the JSON data returned by an API request using Express and compression, but unfortunately it did not work as expected. var express = require('express'); var ...

Integrate a fresh component and include a hyperlink to the URL simultaneously

Seeking to create a system where clicking an item in the navbar loads a new component on the screen, I am faced with the challenge of maintaining state while also updating the URL. Allow me to provide more details: Below is my current navbar code snippet: ...

Utilizing only a fraction of my dataset, I created a barplot in D

My d3.js barplot is based on JSON data with 12 elements. The 'fpkm' value determines the bar height, but only half of the elements are showing up correctly. When I use the data callback function in d3, it only returns values for the first half o ...

The hamburger menu on the responsive navbar fails to open when clicked on

Having an issue with my navbar in mobile and responsive environments. The hamburger menu shows up, but when clicked on, the links are not displayed. Below is the code that I am using, all the necessary links are included but the menu is not functioning pro ...

Select various items simultaneously by pressing Ctrl and access them via form submission

Currently, I have a form with a list of days displayed. When a user clicks on a day, jQuery is used to populate a hidden field with the selected value. This allows me to reference the value in the post array. I now want to enhance this functionality by en ...

Converting user input from a string to an object in JavaScript: a comprehensive guide

Is there a way to transform user input string into objects when given an array of strings? ["code:213123", "code:213123", "code:213123"] I am looking to convert this array into an array of objects with the following format: [{code: "213123"},...] ...