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

后端 未结 2 355
清歌不尽
清歌不尽 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:17

    Sheet1

    ID NUMBER   NAME        DEPARTMENT
    784         John Steep  I.T.
    901         Liz Green   H.R.
    

    Sheet2

    ID NUMBER   NAME        DEPARTMENT
    784         John Steep  I.T.
    653         Bo Gore     Marketing
    

    Sheet3

    ID NUMBER   NAME        DEPARTMENT
    784         John Steep  I.T.
    999         Frank White Sales
    121         Abid Jones  Engineering
    901         Liz Green   H.R.
    

    Script

    function main() {
      var ss = SpreadsheetApp.openById("ID");
    
      var s1 = ss.getSheetByName("Sheet1");  
      var s2 = ss.getSheetByName("Sheet2");  
      var s3 = ss.getSheetByName("Sheet3");  
    
      var idCol = 1;  // Assuming location of ID column is same in all sheets.
    
      var s1RowCount = s1.getLastRow();  
    
      for (var i = 2; i <= s1RowCount; i++) {  // Start at var i = 2 to skip the 
                                               // first row containing the header.
        var id = s1.getRange(i, idCol, 1, 1).getValue();
        deleteDuplicates(s2, id);
        deleteDuplicates(s3, id);
      }
    }
    
    function deleteDuplicates(sheet, id) {
      var idCol = 1; // Assuming location of ID column is same in all sheets.
      var rowCount = sheet.getLastRow();
      for (var i = 2; i <= rowCount; i++) {
        var data = sheet.getRange(i, idCol, 1, 1).getValue();
        if (data === id) {
          // Use this to test out the function.
          Logger.log("Duplicate of ID " + id + " in sheet " + 
              sheet.getSheetName() + " at row " + i);
          // Uncomment the next line when ready.
          // sheet.deleteRow(i);
        }
      }
    }
    

    Logging Output

    [14-11-04 09:16:04:551 PST] Duplicate of ID 784 in sheet Sheet2 at row 2
    [14-11-04 09:16:04:587 PST] Duplicate of ID 784 in sheet Sheet3 at row 2
    [14-11-04 09:16:04:727 PST] Duplicate of ID 901 in sheet Sheet3 at row 5
    

提交回复
热议问题