Search code examples
excelvbaloopsconcatenation

How to Loop through a Column of Cells and Concatenate Adjacent Cells into a New Cell?


I have two columns, one has a list of names and the other contains whether those names are "accepted" or "synonyms".

If a cell's value is "synonym" then I want to add the adjacent value from the first column to a blank cell followed by "; ".

As the program loops, I would like the following "synonym" names to be concatenated to the same cell, again followed by a semi colon and a space.

The code does not run.

Private Sub CommandButton1_Click()
     
    Dim y As Integer, acc As String, syn As String

    y = 159
    'acc is the blank cell for the concatenated strings
    acc = Cells(9, 158).Value
    syn = " "

    Do While y < 165
        If Cells(5, y).Value = "synonym" Then
            syn = Cells(4, y).Value
            acc = acc & syn.Value & "; "
        End If
       y = y + 1
   
   Loop

End Sub

Solution

  • Do Loop

    Option Explicit
    
    Private Sub CommandButton1_Click()
         
        Dim x As Long
        Dim rng As Range
        Dim acc As String
        Dim syn As String
        
        x = 159
        
        Do While x < 165
            If Cells(x, 5).Value = "synonym" Then
                syn = Cells(x, 4).Value
                acc = acc & "; " & syn
            End If
            x = x + 1
        Loop
        acc = Right(acc, Len(acc) - 2) ' "-2" the length of "; "
        Set rng = Cells(158, 9)
        rng.Value = acc
    
    End Sub