rakesh bhat
rakesh bhat

Reputation: 53

How to execute multiple functions in google apps script in order?

Thanks in advance for your time here. I am self taught and new to coding, hence apologies if the question below is something an average programmer should already know.

I have created multiple functions in a single gas file, which when run individually calculate various aspects of same expenses data. But I need all functions to run in order to reach my end goal, which unfortunately I am unable to achieve. Please see examples below.

  1. Both functions when Run individually work without issues.

    function totalSpend(){
    var ss = SpreadsheetApp.getActiveSheet();
    var rt = ss.getRange("K2").getValue();
    var pt = ss.getRange("K1").getValue();
    var ts =  rt + pt ;
    ss.getRange("K3").setValue(ts); }
    
    function perHead(){
    var ss = SpreadsheetApp.getActiveSheet();
    var ts = ss.getRange("K3").getValues();
    var ph = ts / 2;
    ss.getRange("K4").setValue(ph);}
    
  2. But if I combine them both under a single function and then run, nothing happens. I tried using debugger and Execution Transcript but didn't have any luck. Below is example which doesn't work.

    function expCalc(){
    
    function totalSpend(){
    var ss = SpreadsheetApp.getActiveSheet();
    var rt = ss.getRange("K2").getValue();
    var pt = ss.getRange("K1").getValue();
    var ts =  rt + pt ;
    ss.getRange("K3").setValue(ts); };
    
    function perHead(){
    var ss = SpreadsheetApp.getActiveSheet();
    var ts = ss.getRange("K3").getValues();
    var ph = ts / 2;
    ss.getRange("K4").setValue(ph);};
    
    }
    

Upvotes: 5

Views: 30653

Answers (1)

ScampMichael
ScampMichael

Reputation: 3728

function expCalc(){
  totalSpend();
  perHead();
}

function totalSpend(){
var ss = SpreadsheetApp.getActiveSheet();
var rt = ss.getRange("K2").getValue();
var pt = ss.getRange("K1").getValue();
var ts =  rt + pt ;
ss.getRange("K3").setValue(ts); }

function perHead(){
var ss = SpreadsheetApp.getActiveSheet();
var ts = ss.getRange("K3").getValues();
var ph = ts / 2;
ss.getRange("K4").setValue(ph);}

or

function expCalc(){

var ss = SpreadsheetApp.getActiveSheet();
var rt = ss.getRange("K2").getValue();
var pt = ss.getRange("K1").getValue();
var ts =  rt + pt ;
ss.getRange("K3").setValue(ts);

var ts = ss.getRange("K3").getValues();
var ph = ts / 2;
ss.getRange("K4").setValue(ph);
}

Upvotes: 13

Related Questions