Chapter 2 Read, repeat, branch ・ MISSION 8

Mission 8: Loop through every row with for (getLastRow)

📋 Mission list

Task

Write the amount (unit price × quantity) for every item in column D. Find the last row with getLastRow so the code still works when the number of items changes.

Office supply order sheet - Google Sheets
Office supply order sheet

For practice, the table goes back to its starting state every time before the code runs (a real spreadsheet doesn't go back. Script changes can sometimes be undone with Ctrl+Z, but not all at once).

Apps ScriptUntitled projectDeploy ▾
function writeAmounts() {
const sheet = SpreadsheetApp.getActiveSheet();
const lastRow = sheet.();
for (let row = ; row <= lastRow; row++) {
const price = sheet.getRange(row, 2).getValue();
const quantity = sheet.getRange(row, 3).getValue();
sheet.getRange(row, ).setValue(price * quantity);
}
}
Ctrl+S: save · Ctrl+R: run (editor) · F5: reopen

Chapter 2 ・ MISSION 8

Loop through every row with for (getLastRow)

Write the amount (unit price × quantity) for every item in column D. Find the last row with getLastRow so the code still works when the number of items changes.

Now
Goal

Reading the code

const lastRow = sheet.getLastRow();
Finds the number of the last row with a value.
for (let row = 2; row <= lastRow; row++) {
Repeats the block in { } while increasing row by 1 from 2 to lastRow.
sheet.getRange(row, 2).getValue();
Reads row "row", column 2 (column B).
sheet.getRange(row, 4).setValue(price * quantity);
Writes the amount to column D of row "row".

for (let row = 2; row <= lastRow; row++) repeats the block while row goes 2, 3, 4 … one at a time. The row in getRange(row, 4) is the row number. If you find the last row with getLastRow(), you can keep using the code as items are added.

How to get started with GAS and common code are covered in an article.What is GAS? Getting started and common code

The code you write runs in an isolated place inside this page. It can't reach outside the page or other sites.

* This is a simulation of how Google Sheets and Apps Script behave and may differ in some ways from the real thing.

* Google Sheets is a trademark of Google LLC. This site is not affiliated with Google.