Home > Software engineering >  Loop only over a specific set of range of cells in a spreadsheet in apps script
Loop only over a specific set of range of cells in a spreadsheet in apps script

Time:10-31

I have a column to loop and check for a value, the challenge is that the data starts from but not a specific end cell.

Let's say, the data always starts from B4 but may end at any cell in the Column B.

Column B
Type 1
Type 2
Type 3
Type 4
Type 5

I want to loop starting from B4 and read cells down below until it finds an empty cell and the loop should break out.

I wanted to read cell values of the whole range and the do an If - else check, but was thinking of a more easy way to do.

Please help!

CodePudding user response:

To get all non-blank values in column B, use this pattern:

  const sheet = SpreadsheetApp.getActiveSheet();
  const values = sheet.getRange('B1:B')
    .getValues()
    .flat()
    .filter(String);

This gives you a 1D array that is easy to process with Array.map(), Array.forEach() and the like.

  • Related