D
D
delongeroman2020-07-30 13:12:17
Google Apps Script
delongeroman, 2020-07-30 13:12:17

How to check for an empty cell in Google Sheets?

I have a loop that goes through the cells and I need it to stop when this cell is simple, the getLastRow and getLastColumn methods will not work.
The column lists names. I need a condition for stopping this loop so that it does not execute a static number of times, but how many rows I have filled.

The code is something like this:

var ss = SpreadsheetApp.getActiveSpreadsheet()
  var as = ss.getActiveSheet()
  for(var i = 0; i< 1000; i++){ 
      var name = as.getRange(2+i, 1).getValue()
}

Answer the question

In order to leave comments, you need to log in

2 answer(s)
G
Grigory Boev, 2020-07-30
@delongeroman

do {
  // тело цикла
 let name = as.getRange(2+i, 1).getValue()
} while (name!="");

M
Maxim Stoyanov, 2020-07-30
@stomaks

Try something like this:

const ss = SpreadsheetApp.getActiveSpreadsheet();
  const sss = ss.getActiveSheet();
  const sss_max_rows = ss.getMaxRows();
  const sss_frozen_rows = 2; // ss.getFrozenRows() + 1;
  const sss_values = sss.getRange(sss_frozen_rows, 1, sss_max_rows-sss_frozen_rows, 1);

  sss_values.some(function (item, i) {
    let name = item[0];

    // Остановить цикл как только встретим пустую ячейку
    if ( name == "" ) return true;

    // Тут ваш код ...
  });

Please note that you get data from the table 1000 times in a loop, this is bad for the speed of the script.
It is better to take the data once and then go through the array.
---
Maxim Stoyanov (stomaks), developer of Google Apps Script .
g-apps-script.com
stomaks.me

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question