Google Sheets App Script For Loop: How to Use

How-to basics · Updated November 23, 2026

The direct answer: a for loop in Google Apps Script (the scripting language behind Google Sheets) repeats a block of code a set number of times, and the most common use is iterating through rows and columns to read or write cell values. You write it as for (var i = 0; i < 10; i++) { ... } inside a custom function or a macro, then run it from the Extensions menu.

What Apps Script For Loops Actually Do

Apps Script is JavaScript-based, so the for loop works exactly like in JavaScript. The basic syntax is:

function loopThroughRows() {
  var sheet = SpreadsheetApp.getActiveSheet();
  var lastRow = sheet.getLastRow();
  for (var i = 1; i <= lastRow; i++) {
    var value = sheet.getRange(i, 1).getValue();
    Logger.log(value);
  }
}

This loops from row 1 to the last row with data, reads column A, and logs each value. The loop variable i starts at 1 (row 1), continues while i <= lastRow, and increments by 1 each pass. You can change the start, condition, and increment to control exactly which cells you touch.

Why You Need a Loop in Google Sheets

Without a loop, you would have to write a separate line for every cell you want to process. That is impractical for sheets with hundreds or thousands of rows. Loops let you apply the same logic to an entire column, copy data between sheets, clean up duplicates, or send emails based on spreadsheet content. For example, a loop can check each row for a certain status and then update a cell in that row—something formulas alone cannot do because formulas cannot modify other cells.

How to Write a For Loop in Apps Script

Open your Google Sheet, go to Extensions > Apps Script. Delete the default code and paste your function. There are three common patterns:

  • Forward loop: for (var i = 1; i <= 10; i++)—runs 10 times, i = 1,2,...,10.
  • Backward loop: for (var i = lastRow; i >= 1; i--)—useful when deleting rows, because deleting shifts rows up.
  • Step loop: for (var i = 1; i <= 100; i += 2)—every other row.

Inside the loop, use getRange(row, column) to access a specific cell. Remember that Sheets is 1-indexed: row 1 is the first row, column 1 is column A. After writing a function, click the Run button (the triangle icon) to execute it. The first time, you will need to authorize the script to access your sheet.

Common Mistakes and How to Avoid Them

Most beginners hit a few predictable issues:

  • Infinite loop: If your condition never becomes false (e.g., i <= lastRow but you never increment i), the script will time out. Always ensure the variable changes.
  • Off-by-one errors: Using 0 as the start when Sheets rows start at 1. If you start at 0, you read row 0 which does not exist.
  • Slow performance: Calling getValue() and setValue() inside a loop is slow because each call is a network request. Instead, read the entire range into an array, loop through the array, then write the array back in one call.

Example of the faster array method:

function fastLoop() {
  var sheet = SpreadsheetApp.getActiveSheet();
  var range = sheet.getRange(1, 1, sheet.getLastRow(), 1); // column A
  var values = range.getValues(); // 2D array
  for (var i = 0; i < values.length; i++) {
    if (values[i][0] > 100) {
      values[i][0] = "High";
    }
  }
  range.setValues(values);
}

This reads all values at once, modifies the array, and writes back in one operation—much faster for large sheets.

For Loop vs. forEach vs. while

Apps Script also supports forEach and while. A forEach is cleaner when you have an array and do not need the index:

var values = [1,2,3];
values.forEach(function(value) {
  Logger.log(value);
});

A while loop is useful when you do not know how many iterations you need, like reading until an empty cell. However, the classic for loop is the most predictable for row/column iteration because you control the start, end, and step. Use for when you know the exact range; use while for condition-based loops.

Real-World Example: Marking Rows Based on a Condition

Suppose you have a list of sales amounts in column B (rows 2 to 100) and you want to put "Yes" in column C if the amount is greater than 500. Here is a complete function:

function markHighSales() {
  var sheet = SpreadsheetApp.getActiveSheet();
  var lastRow = sheet.getLastRow();
  var amounts = sheet.getRange(2, 2, lastRow - 1, 1).getValues();
  var output = [];
  for (var i = 0; i < amounts.length; i++) {
    if (amounts[i][0] > 500) {
      output.push(["Yes"]);
    } else {
      output.push(["No"]);
    }
  }
  sheet.getRange(2, 3, output.length, 1).setValues(output);
}

This reads all amounts at once, loops through the array, builds a new array of results, and writes it back to column C. Note that the array index starts at 0, but the sheet row starts at 2, so the mapping is correct.

Performance and Quota Limits

Apps Script has daily quotas for triggers and service calls. A simple for loop that reads and writes a few hundred cells is fine, but if you loop over 50,000 cells with individual getValue() calls, you will hit the limit. Use batch operations (getValues/setValues) and avoid running loops inside onEdit triggers that fire for every edit. Also, be aware that a script that runs longer than 6 minutes will time out for a regular user. For very large datasets, consider using SpreadsheetApp.flush() sparingly or splitting the work into chunks.

Frequently Asked Questions

How do I loop through all rows in a Google Sheet?
Use getLastRow() to find the last row with data, then loop from 1 to that number. Example: for (var i = 1; i <= sheet.getLastRow(); i++). But if you have empty rows in between, you might need to loop to a fixed maximum or use getDataRange() to get the full range of cells that contain data.

Can I use a for loop in a cell formula?
No, spreadsheet formulas do not support loops. Apps Script is a separate environment. If you need to repeat an operation on many cells, use array formulas (like ARRAYFORMULA) or write an Apps Script function.

Why does my loop only run once?
Check that your condition is correct. If you use i <= 1, it runs once. Also, if you modify the sheet inside the loop (like deleting rows), the lastRow changes, so your loop may stop early. Use a backward loop when deleting rows.

How do I stop an infinite loop in Apps Script?
If your script is running too long, you can close the browser tab or go to the Apps Script editor and click the red stop button. But the best fix is to add a safety counter, like if (i > 10000) break; inside the loop.

Is there a difference between for and for...in in Apps Script?
Yes, for...in iterates over object properties, not array elements. In Apps Script, you should use a regular for loop or forEach for arrays. Using for...in on an array can produce unexpected results because it includes extra properties.

Can I run a loop every time the sheet is edited?
Yes, you can create an onEdit trigger, but it runs with limited quotas and should be very fast. Avoid heavy loops in onEdit; instead, use a custom menu or a time-driven trigger for large operations.

Related

Try it: the Date Difference Calculator: days, months, years and weekdays between two dates, with the DATEDIF formulas.

More in How-to basics

Sources: Function behaviour and menu paths: Microsoft Support documentation for Excel. Method & sources

Spotted an error in this guide? Let us know.