Home » excel » excel – Writing non-matching data in Col3 from Text in Col1 and Col2

excel – Writing non-matching data in Col3 from Text in Col1 and Col2

Posted by: admin May 14, 2020 Leave a comment

Questions:

I have 2 sets of data, one is a list of part numbers with revision (some with no revision) and a list of the same parts sans revision. These have been manually entered by administrators over years and now I need to create a set of data that is Part Number, Revision.

Due to whatever insanity occurred in times gone past, the revision can appear at random points in the part number, I get a chill every time I say that!

So I need to compare string 1 to string 2 one letter at a time, populating a temporary string with the differences. String 1 will be with revision, string 2 will be without, and due to human error it’s likely that String 2 may have more than just the revision omitted, so will need to show those for manual checking.

I found something that’s close, but my understanding of VBA is not sufficient to allow me to progress.

Function WORDDIF(rngA As Range, rngB As Range) As String

Dim WordsA As Variant, WordsB As Variant
Dim ndxA As Long, ndxB As Long, strTemp As String

WordsA = Split(rngA.Text, " ")
WordsB = Split(rngB.Text, " ")

For ndxB = LBound(WordsB) To UBound(WordsB)
    For ndxA = LBound(WordsA) To UBound(WordsA)
        If StrComp(WordsA(ndxA), WordsB(ndxB), vbTextCompare) = 0 Then
            WordsA(ndxA) = vbNullString
            Exit For
        End If
    Next ndxA
Next ndxB

For ndxA = LBound(WordsA) To UBound(WordsA)
    If WordsA(ndxA) <> vbNullString Then strTemp = strTemp & WordsA(ndxA) & " "
Next ndxA

WORDDIF = Trim(strTemp)

End Function

I would hope to see each letter in the strings compared, once a mismatch is found in string 2, the revision string is populated with that mismatch. The compare would continue to on the same letter on string 1 until a match is found in string 2. For example:

String 1 = 123-2A3-456
String 2 = 123-23-456
Revision = A

String 1 = 123-2A3-456
String 2 = 123-23-46
Revision = A5
How to&Answers:

Something Like this ?

Function WORDDIF(rngA As Range, rngB As Range) As String

Dim WordsA As Variant, WordsB As Variant
Dim ndxA As Long, ndxB As Long, strTemp As String

Dim a As Integer
Dim b As Integer

a = Len(rngA.Text)
b = 1
txt = ""

For i = 1 To a

    If Mid(rngA.Text, i, 1) = Mid(rngB.Text, b, 1) Then
        b = b + 1
    Else
        txt = txt & Mid(rngA.Text, i, 1)
    End If

Next


WORDDIF = txt

End Function

Demo:

enter image description here

Note: It will only compare 1st string to Second, No Vice Versa. If that’s the requirement you can manipulate the current code accordingly.