Search code examples
excelrowexcel-2007vba

Finding and removing duplicates values from row


I am working in Excel 2007. I have data as per following:

data|-v1-|-v2-|-v2-|-v3-|-v4-|
------------------------------
1     |a   |        |a    |      |b    |

2     |     |c      |d    |      |      |

3     |e   |e      |e   |e     |e    |

I am trying to remove duplicate values from each row. I am doing it manually. Expected output is like this:

data|-v1-|-v2-|-v2-|-v3-|-v4-|
------------------------------
1     |a   |        |     |      |b    |

2     |     |c      |d    |      |      |

3     |e   |       |       |      |     |

How to do this in a quick way?


Solution

  • As already outlined by another user HERE, The following code should resolve this issue for you.

    Sub RemoveDuplicatesInRow()
    
        Dim lastRow As Long
        Dim lastCol As Long
        Dim r As Long 'row index
        Dim c As Long 'column index
        Dim i As Long
    
        With ActiveSheet.UsedRange
            lastRow = .Row + .Rows.Count - 1
            lastCol = .Column + .Columns.Count - 1
        End With
    
        For r = 1 To lastRow
            For c = 1 To lastCol
                For i = c + 1 To lastCol 'change lastCol to c+2 will remove adjacent duplicates only
                    If Cells(r, i) <> "" And Cells(r, i) = Cells(r, c) Then
                        Cells(r, i) = ""
                    End If
                Next i
            Next c
        Next r
    
    End Sub