如何在Google脚本中更新重复行

时间:2019-01-29 04:40:37

标签: google-apps-script google-sheets

TeamB TeamA Master 我尝试将数据从主表复制到按key1拆分的团队表中[工作] 但是检查key2的代码不起作用[更新重复行和不重复行]

代码:https://docs.google.com/document/d/1vqbwZqN4XLPmPhat0Jn4Vrg6POvlHfMiaIxfrYI4ajk/edit?usp=sharing

2 个答案:

答案 0 :(得分:0)

您尝试更新的行数似乎不正确。它应该只是1,因为您要更新一行。

语法是:getRange(row,column,numRows,numColumns)

错误范围是:

 Tim1.getRange(j+1,2,aaa[0].length,aaa[0].length).setValues(aaa); //****Update Duplicate Row

应该是这样的:

 Tim1.getRange(j+1,2,1,aaa[0].length).setValues(aaa); //****Update Duplicate Row

答案 1 :(得分:0)

我稍稍更改了代码,因此现在可用于TEAM-A。您可以对Team-B进行相同的操作,请参见代码中的注释。我检查当前值是否已经在工作表中,如果不是,则将其添加到新的行数组中。

function MastertoBrance() {
  //Source SpreadSheet (MasterSpreadSheet)
  var mss = SpreadsheetApp.getActive();
  var mim = mss.getSheetByName("Master"); //Master in Master
  var Tim1 = mss.getSheetByName("TEAM-A"); //Team in Master1
  var Tim2 = mss.getSheetByName("TEAM-B"); //Team in Master2

  // KeepValues (Row,Column,NumRows,NumCols)
  var mdata = mim.getRange(3,2,mim.getLastRow() -1,mim.getLastColumn()).getValues();
  var Tim1data = Tim1.getRange(3,2,Tim1.getLastRow() -1,Tim1.getLastColumn()).getValues();

  var aaa =[];
  var bbb =[];

  for (var i = 0; i < mdata.length; i++) {

    var rValue = mdata[i][3];//4 = No.Column for monitor(E column) keepStartcol2 E=3

    if (rValue == "Team-A") {
      aaa.push(mdata[i]);
    } else if (rValue == "Team-B") {
      bbb.push(mdata[i]);
    }
  }

  if(aaa.length > 0) {
    var newRows = [];

    aaa.forEach(function (row) {
      Logger.log(row);
      var updated = false;
      if(Tim1data.length > 0) {
        Tim1data.some(function (existingRow, idx) {

          // check we found the same row
          if (row[0] === existingRow[0]) {            

            // update row
            // +3 skips the header rows
            Tim1.getRange(idx+3,2,1,row.length).setValues([row]);

            // done
            updated = true;          
            return updated;
          }
        });
      }

      // if we didn't update the data push to new rows array
      if(!updated) {
        newRows.push(row);
      }
    });

    // check we found new rows 
    if(newRows.length > 0) {
      // add all new rows at once Tim1.getRange(Tim1.getLastRow()+1,2,newRows.length,newRows[0].length).setValues(newRows);
    }
  }
}