Take values ​from one sheet and save them on the other sheet based on the ID

﹥>﹥吖頭↗ 提交于 2021-01-29 15:34:11

问题


I tried to create a script that takes values ​​from one sheet and saves them on the other sheet based on the ID. Unfortunately, the script only saves the first value. What's wrong?

function script1() 
{

  // get first sheet 
  var Kwoty = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Kwoty");
  var FirstRow = 10;
  var LastRow = Kwoty.getLastRow();
  var RowRange = LastRow - FirstRow + 1;
  var WholeRange = Kwoty.getRange(FirstRow,6,RowRange,8);
  var AllValues = WholeRange.getValues();
  //Logger.log(AllValues); 
  
  //get 2 sheet
  var rozliczenie = Kwoty.getRange('G6').getValue();//Get sheet name
  var docelowysheet = SpreadsheetApp.openById('1_QgbLn9gKowDhCOwZ8lY9XBe5JmN107xhGDJ2kaGJIE').getSheetByName(rozliczenie);
  var FirstRow2 = 3;
  var LastRow2 = docelowysheet.getLastRow();
  var RowRange2 = LastRow2 - FirstRow2 + 1;
  var WholeRange2 = docelowysheet.getRange(FirstRow2,1,RowRange2,13);
  var AllValues2 = WholeRange2.getValues();
  //Logger.log(AllValues2); 
  
  
  for (var i=0;i<AllValues.length;i++){
     var CurrentRow = AllValues[i];
     var Id1 = CurrentRow[0]; //col with ID Sheet1 
     var kwota = CurrentRow[7]; //col with rate Sheet 1
    Logger.log(CurrentRow); 
     
  for (var i=0;i<AllValues2.length;i++){
     var CurrentRow2 = AllValues2[i];
     var Id2 = CurrentRow2[0]; //Col with ID Sheet2  
     var kwota2 = CurrentRow2[12]; //Col with rate Sheet2
   //Logger.log(Id2);  
     
  //Set Values   
    if (Id1 == Id2){
     var setRow2 = i + FirstRow2;
    docelowysheet.getRange(setRow2, 13).setValue(kwota);
    //Logger.log(CurrentRow[7]);
 
  } 
  }
  }
}

回答1:


Most likely the inconsistency arises in the for loop as you are using the same variable i as iterator for both the main and inner loops, as a result the values overwrite. Change the second loop variable, for example to j (and its references in the internal loop), for example:

for (var i=0;i<AllValues.length;i++){
   var CurrentRow = AllValues[i];
   var Id1 = CurrentRow[0]; //col with ID Sheet1 
   var kwota = CurrentRow[7]; //col with rate Sheet 1
   Logger.log(CurrentRow); 
     
   for (var j=0;j<AllValues2.length;j++){
      var CurrentRow2 = AllValues2[j];
      var Id2 = CurrentRow2[0]; //Col with ID Sheet2  
      var kwota2 = CurrentRow2[12]; //Col with rate Sheet2
      //Logger.log(Id2);  
     
      //Set Values   
      if (Id1 == Id2){
        var setRow2 = j + FirstRow2;
        docelowysheet.getRange(setRow2, 13).setValue(kwota);
        //Logger.log(CurrentRow[7]);
      } 
}


来源:https://stackoverflow.com/questions/65863444/take-values-from-one-sheet-and-save-them-on-the-other-sheet-based-on-the-id

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!