How to use the function .getLastRow() in google script

29,032

getLastRow is a method of classes Sheet and Range, which simply means that whenever you write something.getLastRow(), that something must be a sheet or a range. (As Zig Mandel noted, there is an issue concerning the functionality of the range method; normally it's used for a sheet.)

In your code, activeSheetOne is a sheet, applying getRange("E3:E") you get a range, and then applying getValues() you get just an array of values. This means an ordinary JavaScript array with which you work using JavaScript methods and properties, not Google Apps Script methods.

So, replace the line var lastRow = readingGender.getLastRow(); by

var lastRow = readingGender.length;

where length is the length of an array.

Also, your code with both i and loopVar is a mix of for and while loops. You don't need both; a for loop will do.

for (var i=0; i < lastRow; i++) {
  Logger.log(readingGender[i][0]);
}

Suggestion: learn the fundamentals of JavaScript, e.g., with Codecademy, before working with Google Apps Script.

Share:
29,032
Marcus Fong
Author by

Marcus Fong

Updated on November 30, 2022

Comments

  • Marcus Fong
    Marcus Fong over 1 year

    I'm pretty new to Google Script and I've been working on a line of code that is bothering me right now. What I'm trying to do is make the computer read through a range of cells in the spread sheet, then print them all out, but stop at the last row. But, as I've tried using the function .getLastRow() in the for loop or just making a variable, it doesn't work. (There are some parts where the code is redundant and not related to the problem so you can ignore that.)

    function myFunction()
    {
    
      var spreadSheet = SpreadsheetApp.openById("1F4zEJXKN3iobK8b89Ub94dd77Tdk70H0X8aFCSCmvRs");
      var activeSheetOne = spreadSheet.getSheetByName("New Family Responses");
      var activeSheetTwo = spreadSheet.getSheetByName("Existing Family Responses");
    
      var readingGender = activeSheetOne.getRange("E3:E").getValues();
      var lastRow = readingGender.getLastRow();
      var loopVar = 0;
    
      for (var i=0; i < lastRow; i++) {
        Logger.log(readingGender[loopVar][0]);
        loopVar = loopVar + 1;
      }
    
    }
    
  • Zig Mandel
    Zig Mandel about 8 years
    be aware that range.getLastRow() is currently the same as sheet.getLastRow() see code.google.com/p/google-apps-script-issues/issues/…
  • Admin
    Admin about 8 years
    Good point; I never used it for a range myself, and was going off the code in the question. Edited.