Home > front end >  Set function output as a variable for another function (GAS)
Set function output as a variable for another function (GAS)

Time:01-17

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})

}
   

CodePudding user response:

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.`);
}

CodePudding user response:

You want to lunch it from that loop? You have to do it the other way, not from saveData, but from the first function.

Name the function as function saveData(editRow) and call it from your loop by naming it and putting inside the variable: saveData(i 1)

PS: delete the definition of editRow in your function, the line that says var editRow...

  • Related