简体   繁体   English

将 function output 设置为另一个 function (GAS) 的变量

[英]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在 Google Apps 脚本中,我希望使用 function rowOfEmployee 的 output 作为 function saveData 的变量(editrow)

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

}
   

You want to lunch it from that loop?你想从那个循环中吃午饭吗? You have to do it the other way, not from saveData, but from the first function.你必须用另一种方式来做,不是从 saveData,而是从第一个 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)将 function 命名为function saveData(editRow)并通过命名并放入变量从循环中调用它: saveData(i+1)

PS: delete the definition of editRow in your function, the line that says var editRow... PS:在你的function中删除editRow的定义,说var editRow...

One way is to use Array.indexOf() , like this:一种方法是使用Array.indexOf() ,如下所示:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM