Having a problem with the getLastRow() function because it is returning empty rows in the output, and I specifically need to

I'm having trouble with the getLastRow() function in my script. I want to retrieve the last row with data, but the script returns all rows because there are empty rows below the filled ones. How can I modify it to stop at the last row with data? The data includes an array formula and here's the script snippet to give you a better idea:

function Productivity() 
{
  var ui = SpreadsheetApp.getUi();
  var response = ui.alert('Do you want to send emails to all PRICE ACCURACY resources now?', ui.ButtonSet.YES_NO);
  // Process the user's response.
  if (response == ui.Button.YES) 
  {
    
    var ss = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('Productivity Report Out')
    var range = ss.getDataRange().getValues()
    var lastrow = ss.getLastRow();
    //Logger.log(range.length)
    for(var i=1;i<=lastrow; i++) //i<range.length

    {
      Logger.log("Index:"+i+" | ["+range[i]+"]")
      var status =  range[i][14]
      if(status !='No')
      {
        var name =  range[i][0]
        var ldap = range[i][1]
        var target = range[i][2]
        var new_mvt = range[i][3]
        var onboarding = range[i][4]
        var ubio_rates =  range[i][5]
        var violation = range[i][6]
        var reevaluation = range[i][7]
        var total = range[i][8]
        var current_productivity = range[i][9]
        var deficit = range[i][10]
        var remaining_checks = range[i][11]
        var week = range[i][12]
        var date = range[i][13]

Answer №1

You previously defined the variable lastRow, but it appears to be unused.

It seems like you may be trying to iterate through all rows using this logic:

for(var i=1; i<=lastRow; i++)

The method .getLastRow() is designed to return the position of the last row with data, as explained in the documentation:

Returns the position of the last row that has content.

Just a side note: If your sheet doesn't have a header row, make sure to start your loop at index 0 (row 1) instead of 1 (row 2).

Answer №2

Dealing with empty rows in your dataset

If the status is not equal to 'No'
, it could result in a blank row. It's possible that an Array Formula is causing inaccuracies in the calculation of getLastRow(). Try using Logger.log(lastRow) to verify its correctness.

Implement this custom function:

function getColHeight(col, sh, ss) {
  var ss = ss || SpreadsheetApp.getActive();
  var sh = sh || ss.getActiveSheet();
  var col = col || sh.getActiveCell().getColumn();
  var rcA = [];
  if (sh.getLastRow()){ rcA = sh.getRange(1, col, sh.getLastRow(), 1).getValues().flat().reverse(); }
  let s = 0;
  for (let i = 0; i < rcA.length; i++) {
    if (rcA[i].toString().length == 0) {
      s++;
    } else {
      break;
    }
  }
  return rcA.length - s;
}

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

JQuery horizontal navbar hover animations

Looking to design a simple navigation bar that displays a submenu when hovering over a link. The issue I'm facing is that the submenu disappears when moving from the link to the submenu itself, which is not the desired behavior. How can this be fixed ...

What is the rationale behind assigning a random value to the `(keyup)` event in order to update template local variables in Angular2?

To update #box in <p>, I need to give a random value to the (keyup) attribute. Here's an example: <!-- The value on the right of equality sign for (keyup) doesn't matter --> <input #box (keyup)="some_random_value" placeholder ...

What is a way to receive a reply in JavaScript without using an endpoint?

Take a look at this code snippet I wrote: ... await fetch('https://example.com', { method: "GET", mode: "no-cors" }) .then((response) => { console.log(response.body); console.log(response ...

Utilize jQuery to cycle through images as the background of a div

Whenever I hover over a div, it successfully cycles and changes the background-image, while stopping the other divs from cycling. The issue arises when each div has a title that appears upon hovering, and if I quickly move my cursor from one title to anot ...

Wait for response after clicking the button in Vue before proceeding

When the button is clicked for the first time and the data property is empty, I need to pause the button click code until an ajax response is received. Currently, when I press the button, both wait and scroll actions happen immediately without waiting for ...

attaching the model to chosen values rather than defining the chosen item

This is the coding I am currently using which is functioning correctly: <div class="col-md-12"> <div class="button-group"> <button type="button" class="btn btn-default btn-block btn-sm dropdown-toggle" data-toggle="dropdown"> ...

passing JSON data to an Express server

I've searched numerous articles on how to send JSON to Express via POST, but none of the methods have fixed my issue. The problem I'm encountering is that when I try to read req.body where req is the request object, the output I receive is { &ap ...

Transmit specific elements from an array to another array exclusively with Javascript

I have some data stored in a JSON array like this: source=[{"OperationName":"All","PrivilegeName":"Roles CRUD"}, {"OperationName":"Read","PrivilegeName":"Roles Read Delete"}, {"OperationName":"Delete","PrivilegeName":"Roles Read Delete"}, ...

The best way to dynamically render HTML based on screen size using server-side rendering in Vue/Nuxt

Imagine having specific markup that should only be displayed on desktop using v-if. If the user is on mobile, a different content should be shown using v-else. The vue-mq package allows for setting a default breakpoint to use for server-side rendering. ...

choose all the choices with jQuery

Is there a way to implement a select all feature for an option list using jQuery? Basically, I want to be able to select all the option elements within the same class (class 11) when the parent option (Option Pa1) is selected. How can this be achieved? ...

Tips for invoking a .NET function from JavaScript in a Windows Phone Blank app

How can I invoke a .NET function from JavaScript within my Windows phone blank App? I am designing the user interface by parsing XML, and the function name is retrieved as a string from the XML. What is the best way to call this function? ...

Experimenting with AngularJS 1.6 class-oriented controllers through the lens of Jasmine/Karma testing

Struggling to use jasmine/karma to test my class-based controllers, unfortunately without any success. Most examples I come across are dated back to 2014 or older. I've made sure to load the angular and angular-mock files in my karma configuration fil ...

What is the best way to organize angularjs controllers and directives within one another?

When I structure my controllers like this: <body ng-app="app" ng-controller="ctrl"> <div ng-controller="app-get"> <app-get></app-get> </div> <div ng-controller="app-post"> <app-post">& ...

Error message: "An issue occurred: Unable to access undefined properties (specifically, borderRadius) in MUI react."

I recently created a navigation bar with an integrated search bar component. The styling for my search component was done using MUI styled from @emotion/styled in MUI library, where I applied a borderRadius: theme.shape.borderRadius. However, I encountere ...

Encountering a problem in a NextJS application where an error occurs stating "cannot read property of undefined (reading setState)" within

In an attempt to resolve the issue, I have linked the method to this inside the constructor. Additionally, I have utilized the arrow function technique to address the problem at hand. Despite these efforts, I continue to encounter the following error: Unha ...

Node.js equivalent of Java's byteArray

I have a Node.js REST API with images being sent from a Java application as byte arrays. Here is an image Below is the string representation of the image in byte array form: [B@c75af72 I need to decode this byte array to verify if it is indeed an ima ...

Utilizing Dashes in Array Indexes

Hey everyone, I'm trying to work with an array that has hyphens in the key name. How can I retrieve the value of it in PHP? Whenever I try accessing it like this, I just get a 0: print $testarray->test-key; This is how the array is structured: ...

Having trouble with my React private route, can't seem to get it to function properly

I'm fairly new to React, and I've set up a private route with an authToken passed through props from the state of App.js. The idea is that if the authToken is true, the private route should direct me to /HomePage, but whenever I log in with valid ...

Is it possible to use TypeScript to create objects in a specific pattern from an array of objects and retrieve data using a for loop?

Having trouble with a for loop while converting an array of objects into a single object. In my Node.js app, I have the following object: Currently working on a REST API and need to properly handle the response. [ { "issuer_id" ...

"Step-by-step guide on triggering the ng-click function for the first row within an ng

I'm facing an issue where the first set of data from the ng-repeat div is not loading before clicking on the ng-repeat. Below is the code snippet: <div class"profile" ng-repeat="data in information" ng-click="getData(data.i ...