Search code examples
htmlgoogle-apps-scriptgoogle-sheetsline-breaks

How to set the variable in body email to run once?


A body is created with a for loop. I want the sheet.getName() just to run once

So far, the sheet.getName() is looping every line. How can I make the name (battery 2 and battery 3) just to show only once? Below is the screenshot: enter image description here

 if(resultArr.length>0){
 var subject = 'Range exceeded Alert' + "" + sheet.getName();

 //Creates a body through the obtained values

 for(var m=0;m<resultArr.length;m++){
  body+= sheet.getName() + "<br>" + "For Part No "+resultArr[m] 
  [0].toString()+" and Month "+resultArr[m][1]
  .toString()+", Value is "+resultArr[m][2].toString()+"<br>";
            }

        }

I expect the sheet.getName() to be shown only once.


Solution

    • You want to add sheet.getName() of body+= sheet.getName() + "<br>" + "For Part No "+resultArr[m]... only one time at the top of body.

    If my understanding is correct, how about this modification?

    Modification points:

    • In your script, body+= sheet.getName() + "<br>" + "For Part No "+resultArr[m]... is put in the for loop. In order to add sheet.getName() at the top of the body, it moves sheet.getName() to the outside of the for loop.

    Modified script:

    Please modify as follows.

    body += sheet.getName() + "<br>"; // Added
    for(var m=0;m<resultArr.length;m++){
      body+= "For Part No "+resultArr[m][0].toString()+" and Month "+resultArr[m][1].toString()+", Value is "+resultArr[m][2].toString()+"<br>"; // Modified
    }
    
    • In this modification, it supposes that body is declared elsewhere.

    If I misunderstood your question and this was not the result you want, I apologize.