In this post, you’ll learn Google Apps Script For Next loop, syntax and examples explaining how to use For Next loop effectively in the apps scripting.
Table of Contents
Google Apps Script For Next loop
For loop execute a set of statements or instructions for specified number of times. It has the loop index which counts the number iterations as the loop executes.
Syntax of Google Apps Script For Next loop
for(initialization, condition, increment)
Set of instructions to be executed;
Initialization– It is executed only one time when compiler enters into the for loop. Here, you have to declare and initialize for loop counter variable and start value.
Condition – During each iteration, the compiler checks the condition given in this place. It executes the instructions present inside the curly braces only if the condition is true.
Increment– It increments the counter variable after each iteration of For loop.
Example of Google apps script for next loop
In this example, we’ll learn about the Google apps for next loop by printing numbers 1 to 10 in Column A of sheet 1.Go to Google drive -> New -> Google sheets. A new Google sheets will be opened. Enter a sheet name and save it. Go to Tools-> Script Editor. A script editor window will be opened in a new tab. Enter the below code in the script editor, save and execute it.
var wb= SpreadsheetApp.getActiveSpreadsheet();
var cell=sh1.getRange(i, 1);
var wb= SpreadsheetApp.getActiveSpreadsheet(); – getActiveSpreadsheet() method returns the object of currently opened spreadsheet.
var sh1=wb.getActiveSheet(); – getActiveSheet() method returns the currently active sheet in the google sheets app.
for(i=1;i<=10;i++)– Here for loop is initialized with value 1, then it check the condition whether variable i is always lesser than or equal to 10 before executing the loop statement. After each iteration, counter variable i is increased by 1.
var cell=sh1.getRange(i, 1) – getRange(rows, columns) method return the position of cell in a sheet by its rows and column index.
cell.setValue(i);- setValue(Object) method populate the object or value present inside the parenthesis on the specified cell.
Rajan is a web geek-Blogger-Programmer- working in corporate firm as system analyst engineer. Whenever time permits he used to blog on recent trends in technology, monetizing tips, Programming concepts and technical guides to beginners in amarindaz.