Forum Discussion

jukhamil's avatar
jukhamil
Brass Contributor
Sep 24, 2021
Solved

A simple merge function

I'd like to write a simple merge function along these lines:   First, find all identical (duplicate) entries in Column B.   Then, for all columns after column B (in the data range):   Merge the...
  • mtarler's avatar
    Sep 24, 2021

    First I ask if you really want to change the data or create a 'better' way to view the data. I ask because often people treat excel sheets as data collection, storage and viewing when often it is better to have data collection and storage set up separate from data viewing. For example, that is why Excel has Pivot Tables. By the way, you might consider if a Pivot Table view might be adequate for what you want. If not, some the new Dynamic Array formulas could be used to generate a view that you want.
    That all said, if you want to change the data (i.e. use VBA) then I might suggest a slight variation on your pseudo-code:

    Sub mergeDups()
      Dim i, FoundRow, C, LastRow, LastCol As Long
      With ActiveSheet
        LastRow = .UsedRange.Rows.Count
        LastCol = .UsedRange.Columns.Count
        For i = LastRow To 1 Step -1
          For FoundRow = 1 To i
               If (.Cells(i, 1) = .Cells(FoundRow, 1)) Then Exit For
           Next FoundRow
          If (FoundRow < i) Then
             For C = 2 To LastCol
                  If InStr(1, .Cells(FoundRow, C).Value2, .Cells(i, C).Value2) = 0 Then
                         .Cells(FoundRow, C).Value2 = .Cells(FoundRow, C).Value2 & ", " & .Cells(i, C).Value2
                  End If
             Next C
              .Cells(i, 1).EntireRow.Delete
           End If
        Next i
      End With
    End Sub

Resources