Delete row values in more than 1 sheet if exists in another sheet

后端 未结 2 350
清歌不尽
清歌不尽 2021-01-23 09:29

The code below is from an answer from this post regarding copying row values to a new sheet if it exist in another sheets.

Now, what if instead of copying the duplicate

2条回答
  •  清酒与你
    2021-01-23 10:10

    Although the other answer works (I didn't test but I guess it does) it uses a lot of spreadsheetApp calls and might be slow if you have a lot of data.

    It is possible to get this result using only arrays (if you don't need to keep sheet formatting and/or formulas).

    The approach is slightly different as it is easier to keep data instead of removing it.

    There are for sure many possible solutions, below is the one I tried : I created a special array that contains only the first column of sheet3 to make the duplicate search simpler.

    function removeDupsInOtherSheets() {
      var ss = SpreadsheetApp.getActiveSpreadsheet();
      var s1 = ss.getSheetByName("Sheet1").getDataRange().getValues();  
      var s2 = ss.getSheetByName("Sheet2").getDataRange().getValues(); 
      var s3 = ss.getSheetByName("Sheet3").getDataRange().getValues();  
      // iterate s3 and check in s1 & s2 if duplicate values exist
      var nS1 = [];
      var nS2 = [];
      var s3Col1 = [];// data in column1 of sheet3
      for(var n in s3){
        s3Col1.push(s3[n][0]);
      }
      for(var n in s1){ // iterate sheet1 and test col 1 vs col 1 in sheet3
        var noDup1 = checkForDup(s1[n],s3Col1)
        if(noDup1){nS1.push(noDup1)};// if not present in sheet3 then keep
      } 
      for(var n in s2){  // iterate sheet2 and test col 1 vs col 1 in sheet3
        var noDup2 = checkForDup(s2[n],s3Col1)
        if(noDup2){nS2.push(noDup2)};// if not present in sheet3 then keep
      }
      Logger.log(nS1);// view result
      Logger.log(nS2);
      ss.getSheetByName("Sheet1").getDataRange().clear();// clear and update sheets
      ss.getSheetByName("Sheet2").getDataRange().clear();
      ss.getSheetByName("Sheet1").getRange(1,1,nS1.length,nS1[0].length).setValues(nS1);
      ss.getSheetByName("Sheet2").getRange(1,1,nS2.length,nS2[0].length).setValues(nS2);
    }
    
    function checkForDup(item,s){
      Logger.log(s+' = '+item[0]+'  ?')
        if(s.indexOf(item[0])>-1){
          return null;
        }
      return item;
    }
    

提交回复
热议问题