vbaexcelduplicates

Excel VBA find duplicates in 1st 2 columns and then sum rows in 3rd & 4th column


I am trying to make a vba code in excel but fail to do so also having hard time to find a solution on internet.

Example:

     A | B | C | D 

1    Z | Y | 1 | 6
2    Z | Y | 2 | 5
3    Y | Z | 3 | 4
4    X | X | 1 | 2
5    P | Z | 4 | 3
6    P | Z | 5 | 2
7    P | Y | 6 | 1

If Column A1 & A2 are same (Duplicates) then
look in B1 & B2
     if B1 & B2 also duplicates then
          C1 + C2  &  D1 + D2
              and delete rows 2 and 6

After Macro:

     A | B | C | D  

1    Z | Y | 3 | 11
2    Y | Z | 3 | 4
3    X | X | 1 | 2
4    P | Z | 9 | 5
5    P | Y | 6 | 1


rows 2 and 6 were deleted

So if column A contains duplicates, in those duplicate rows look in column B and find duplicates there. If duplicates are also in column B then sum rows in col C & D and delete duplicated row...

Sorry for bad explanation...

Thank you very much, Best Regards, Mario


Solution

  • Another similar solution..

    Sub test()
    Dim i As Integer
    
    i = Range("A65536").End(xlUp).Row
    
    For K = 2 To i + 1
    A = Range("A" & K).Value
    B = Range("B" & K).Value
    
    aup = Range("A" & (K - 1)).Value
    bup = Range("B" & (K - 1)).Value
    
    If A = aup And B = bup Then
    Range("C" & K).Value = Range("C" & K).Value + Range("C" & K - 1).Value
    Range("D" & K).Value = Range("D" & K).Value + Range("D" & K - 1).Value
    
    
    Rows(K - 1).Select
    Rows(K - 1).Delete
    End If
    
    Next
    
    End Sub