Search code examples
variablesgoogle-apps-scriptgoogle-sheetsinputoutput

Set function output as a variable for another function (GAS)


Thanks in advance for helping me with this.

In Google Apps Script I wish to use the output of function rowOfEmployee as a variable (editrow) for function saveData

Can someone help me do this? I'm sure it's something really simple and obvious and I will probably kick myself for not working it out haha

Here are my two codes:

  var datasheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Data");
  var data = datasheet.getDataRange().getValues();
  var employeesheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Save");
  var employee = employeesheet.getRange("B1").getValue();

  for(var i = 0; i<data.length;i++){
    if(data[i][0] == employee){
      Logger.log((i+1))
      return i+1;
    }
  }
  
}
function saveData() {
  var datasheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Data");
  var data = datasheet.getDataRange().getValues();
  var employeesheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Save");
  var employee = employeesheet.getRange("B1").getValue();
  var editrow = rowOfEmployee //Here I want to take the output from the previous function rowOfEmployee
  var col = datasheet.getLastColumn();
  var target = datasheet.getRange(editrow,col +1);
  var saveEntry = employeesheet.getRange("B2").getValue();

  saveEntry.copyTo(target, {contentsOnly:true})

}
   

Solution

  • One way is to use Array.indexOf(), like this:

    function saveData() {
      const ss = SpreadsheetApp.getActive();
      const employeeSheet = ss.getSheetByName('Save');
      const employee = employeeSheet.getRange('B1').getValue();
      const dataSheet = ss.getSheetByName('Data');
      const names = dataSheet.getRange('A1:A').getValues().flat();
      const targetIndex = names.indexOf(employee);
      if (targetIndex === -1) {
        ss.toast(`Name '${employee}' cannot be found.`);
        return;
      }
      dataSheet.getRange(targetIndex + 1, dataSheet.getLastColumn() + 1)
        .setValue(employeeSheet.getRange('B2').getValue());
      ss.toast(`Data saved.`);
    }