Zimox
Zimox

Reputation: 69

For loop in the column

I'm having trouble with loops in a column. My goal is to start another function if any cell in the column B has a value.

Here my code that I tried to readapt thanks to the previous answers.

  let startRow = 2;
  let lastRow = sheet.getLastRow();
  let numRows = lastRow  - startRow;
  let rng = sheet.getRange(2,2).getValues();
  
  for (var i = 0; i < numRows; i++){
    
   let cell = rng[i];

    if (cell !== '') {     
      
      //otherfunction();      
      
    }
  }

The problem is that the other function doesn't start

What I doing wrong?

Thanks

Upvotes: 1

Views: 314

Answers (1)

Marios
Marios

Reputation: 27348

Explanation:

Issue 1:

  • getRange(2,2) specifies only a single cell (B2) but because you use getValues you get a 2D array in the form [[x]].

Therefore when you call rng[i] you get something like [x] which is, again, an array. Therefore, cell !== '' will always be false.

Issue 2:

It seems you want to iterate over column B but you in your code you only consider a single cell, therefore the for loop is not used and in fact rng has only one row (as I explained before).

Solution:

function myFunction() {
  
  let ss = SpreadsheetApp.getActive();
  let sheet = ss.getSheetByName("Sheet1");
  let values = sheet.getRange('B2:B'+sheet.getLastRow()).getValues().flat();
  
  for (var i = 0; i < values.length; i++){
    
   let cell = values[i];

   if (cell !== '') {     
      
      //otherfunction();      
      
    }
  }
}

Upvotes: 1

Related Questions