Search code examples
excelvbafor-loopstring-comparison

Compare 2 ranges add new items to end of range


I have a range in column D and a range in column F. These ranges contain strings, the strings in column D are unique (i.e. they do not repeat) and the strings in column F are also unique. However, column D and F should both contain the same strings most of the time, although they may be in a different order. The strings look something similar to:

tag:(0004)X-axis
tag:(0005)Z-axis
tag:(0005)X-axis
tag:(0006)Z-axis

Sometimes column D may be missing some of the strings or it may have some new strings. I want to compare column D to column F and if there are new strings in column D, I want to add (append) them to the end of column F. Here is a simple Example using simply a,b,c instead of "tag:(00... bla... bla...":

Column D    Column F
a           b
b           c
c           d
e           e
f           g
g

Column D is missing "d" but has "a" and "f"... so "a" and "f" will be added (apended) to the end to column F, like this:

Column F
b
c
d
e
g
a
f

I was trying to use this as a less direct route but I can't even get this to work:

Sub RT_COMPILER()

Dim Lastrow As Long
Dim r As Long
Dim n As Long

For r = 1 To Lastrow
    n = Application.WorksheetFunction.CountIf(Range("D:D"), Cells(r, 6))
    If n = 0 Then
        Cells(r, 7) = Cells(r, 4)
    Else
        Cells(r, 7) = ""
    End If
Next

End Sub

My thinking was: If I could get the new strings into column G... then delete the blank spaces then copy and paste them appending them to the end of column F... but it seems to just identify that the last item in column D is "g" and the last item in column F is blank and it would pull a "g" out of the list even though it already had a "g"...

When I originally found this code it had:

n = Application.WorksheetFunction.CountIf("D:D", Cells(r, 6))

it didn't work so I changed it to:

n = Application.WorksheetFunction.CountIf(Range("D:D"), Cells(r, 6))

Solution

  • Option Explicit
    
    Sub test()
    
        Dim LastrowD As Long, i As Long, LastrowF As Long, Times As Long
        Dim cell As Range, rngToSearch As Range
        Dim str As String
    
        With ThisWorkbook.Worksheets("Sheet5")
    
            LastrowD = .Cells(.Rows.Count, "D").End(xlUp).Row
    
            For i = 1 To LastrowD
    
                str = .Range("D" & i).Value
                LastrowF = .Cells(.Rows.Count, "F").End(xlUp).Row
    
                Set rngToSearch = .Range("F1:F" & LastrowF)
    
                Times = Application.WorksheetFunction.CountIf(rngToSearch, str)
    
                If Times = 0 Then
                    .Range("F" & LastrowF + 1) = str
                End If
    
            Next i
    
        End With
    
    End Sub