You can simulate the behavior of a ForEach loop in Google Sheets, but it doesn't support traditional programming loop structures directly in its formula language.
However, you can achieve similar results using array formulas, Google Sheets functions that can operate on a range of cells, or through Google Apps Script for more complex operations.
Google Sheets has various functions that can operate on each element of a range automatically, similar to a foreach loop. For example, if you want to add 2 to each number in a range (A1:A10), you can use the ARRAYFORMULA function:
=ARRAYFORMULA(A1:A10 + 2)
This formula will add 2 to each cell in the range A1:A10. Functions like SUMIF, COUNTIF, AVERAGEIF, etc., can also perform operations on each item in a range based on certain conditions.
For more complex operations or if you need to perform actions that can't be done with a single formula, you can use Google Apps Script.
Here's a simple example of a foreach loop in Google Apps Script that iterates over each cell in a range and adds 2 to its value:
function addTwoToRange() {
// Specify your spreadsheet ID here
var spreadsheetId = 'YOUR_SPREADSHEET_ID_HERE';
// Open the spreadsheet by ID
var spreadsheet = SpreadsheetApp.openById(spreadsheetId);
// Get the specific sheet by name (replace 'Sheet1' with your sheet's name)
var sheet = spreadsheet.getSheetByName('Sheet1');
var range = sheet.getRange("A1:A10");
var values = range.getValues();
for (var i = 0; i < values.length; i++) {
values[i][0] += 2; // Add 2 to each value
}
range.setValues(values); // Write the updated values back to the sheet
}
Note: Your spreadsheet ID is the long string in the URL of your Google Sheet. For example, in the URL https://docs.google.com/spreadsheets/d/abc123/edit#gid=0, the ID is abc123.
To use this script:
Go to Extensions > Apps Script.
Delete any code in the script editor and paste the above script.
Save the script with a name (e.g. "ForEach Loop").
Run the function addTwoToRange from the Apps Script editor.
The execution log should show that the execution has been completed. The changes should be reflected automatically in your spreadsheet.
We hope that this article has helped you and given you a better understanding of how to set up a Google Sheets ForEach loop. If you enjoyed this article, you might also like our articles on how to make a bracket in Google Sheets and how to change your text to proper case in Google Sheets.