Google Script: Delete row if a value in it exists in another sheet

前端 未结 1 1472
情深已故
情深已故 2020-12-11 11:44

I have a question with Google Scripting. I just started using Google Script this February so I don\'t have deep understanding with it yet. Anyway my question is:

Ca

相关标签:
1条回答
  • 2020-12-11 12:00

    The problem with the 2D array library you use is that the find method returns an integer corresponding to its position in the array, which is not really a helpful information for you in this case. I'd sugggest to loop in both arrays (which is very quick) and use a boolean to determine if we keep (or not) the values in sheet1. Here is the code I used for testing and it seems to work as expected.

    function deleteRowInSheet1() { 
      var s1 = SpreadsheetApp.openById("1RxtFWZJRWxgW-zUM6S-dvZ0yFe-G2DGJFWI3gAt-1T0").getSheetByName('Sheet1');
      var s2 = SpreadsheetApp.openById("1RxtFWZJRWxgW-zUM6S-dvZ0yFe-G2DGJFWI3gAt-1T0").getSheetByName('Sheet2'); 
      var values1 = s1.getDataRange().getValues();
      var values2 = s2.getDataRange().getValues();
      var resultArray = [];
      for(var n in values1){
        var keep = true
        for(var p in values2){
          if( values1[n][0] == values2[p][0] && values1[n][1] == values2[p][1]){
            keep=false ; break ;
          }
        }
        if(keep){ resultArray.push(values1[n])};
      }
      s1.clear()
      s1.getRange(1,1,resultArray.length,resultArray[0].length).setValues(resultArray);
    }
    

    As you can see I delete the whole sheet to rebuild it with a new data array but doing this I loose any formatting that might have been present. If that's an issue for you then you'll have to use clearContents() instead. See doc here but delete any formatting in every unused rows below the last row... not very hard to implement I guess.

    0 讨论(0)
提交回复
热议问题