Feeling Lucky?

How to use For Loops in Apps Script

 Hello everyone,

In this article we will try to create a looping code in Google Apps Script with For Loop. The use of looping code is to run the same formula several times without writing it one by one. 


Let's create rows number in the right side of this table start with 1 :




So, to do this, we could write for loops code in our script.


Basic form of for loops code is :


for (var ...; ....; ...){

 

}

 

“var ….;” is to declare the variable and the initial number.

The middle “….. ;” is to state the maximum or minimum number and to determine the number of iterations.

The right  “….. ;” is to state the formula of looping, can be plus or minus.

 

Here is the code that I add to Apps Script to create number 1 to 4 in cell E4 to E7

 

for ( var i=0; i<4; i++  ){

    activeSheet.getRange(i+4, 5).setValue(i+1);

       

       }

 

i = 0; it means the initial number of the variable i is 0.

i < 4; it means the variable i can’t equal or more than 4.

i++; it means in every iteration the variable i will be added by 1. 

 

Here is my full code :

 

function myFunction() {

  

  var app = SpreadsheetApp.openByUrl("your spreadsheet url");

  var activeSheet = app.getSheetByName("your sheetname");

  var text = activeSheet.getRange(1, 2).getValue();

  

  activeSheet.getRange(4, 1, 4, 4).setValue(text);

  

  for ( var i=0; i<4; i++  ){

    activeSheet.getRange(i+4, 5).setValue(i+1);

       

       }

}

 

And here is the result :

 

 

Okay, that is a tutorial to use for loops code in Apps Script. I hope it can be useful. Thank you

 

 

 

 

 


Comments

Popular posts from this blog

Bagaimana cara bayar pajak 5 tahunan? (Lokasi di Samsat Blitar Kota)

Create Your First Code in Apps Script