Re: VBA code to identify non matching text
I was playing with this some more today and thought you might find it more useful as a function.
Public Function RevDiffStr(string1 As String, string2 As String, First As Boolean)
Dim StringComp1Arr As Variant
Dim stringComp2Arr As Variant
Dim i As Long
Dim j As Long
Dim OutputArr() As Variant
Dim OutputSTR As String
Dim DiffFnd As Boolean
'Split string1 into Array
ReDim StringComp1Arr(Len(string1) - 1)
For i = 1 To Len(string1)
StringComp1Arr(i - 1) = Mid$(string1, i, 1)
Next
'Split string2 into Array
ReDim stringComp2Arr(Len(string2) - 1)
For i = 1 To Len(string2)
stringComp2Arr(i - 1) = Mid$(string2, i, 1)
Next
DiffFnd = False
'change to less than symbol on the following line to return
'the differences in the opposite string
If First Then
If Len(string1) < Len(string2) Then
For i = LBound(StringComp1Arr) To UBound(StringComp1Arr)
If StringComp1Arr(i) <> stringComp2Arr(i) Then
For j = i To UBound(stringComp2Arr)
ReDim Preserve OutputArr(j)
OutputArr(j) = stringComp2Arr(j)
Next j
OutputSTR = Join(OutputArr, "")
DiffFnd = True
Exit For
End If
Next i
Else
For i = LBound(stringComp2Arr) To UBound(stringComp2Arr)
If stringComp2Arr(i) <> StringComp1Arr(i) Then
For j = i To UBound(StringComp1Arr)
ReDim Preserve OutputArr(j)
OutputArr(j) = StringComp1Arr(j)
Next j
OutputSTR = Join(OutputArr, "")
DiffFnd = True
Exit For
End If
Next i
End If
Else
If Len(string1) > Len(string2) Then
For i = LBound(StringComp1Arr) To UBound(StringComp1Arr)
If StringComp1Arr(i) <> stringComp2Arr(i) Then
For j = i To UBound(stringComp2Arr)
ReDim Preserve OutputArr(j)
OutputArr(j) = stringComp2Arr(j)
Next j
OutputSTR = Join(OutputArr, "")
DiffFnd = True
Exit For
End If
Next i
Else
For i = LBound(stringComp2Arr) To UBound(stringComp2Arr)
If stringComp2Arr(i) <> StringComp1Arr(i) Then
For j = i To UBound(StringComp1Arr)
ReDim Preserve OutputArr(j)
OutputArr(j) = StringComp1Arr(j)
Next j
OutputSTR = Join(OutputArr, "")
DiffFnd = True
Exit For
End If
Next i
End If
End If
If DiffFnd = False Then
OutputSTR = "No Differences"
End If
RevDiffStr = OutputSTR
End Function
Display More
You can use it in a formula like this.
Cell A1: I am a boy
Cell A2: I m a boy
Any cell: =RevDiffStr(A1, A2, True)
Would produce result: "am a boy"
Any cell: =RevDiffStr(A1, A2, False)
Would produce result: "m a boy"
The true or false is to determine which of the two strings to produce the result from. True uses the first string, False uses the second string.
or you could also use it in other vba code like this....
Sub TestStrResults()
Dim mySTRvar1 As String
Dim mySTRvar2 As String
Dim result As String
mySTRvar1 = "I am a boy"
mySTRvar2 = "I m a boy"
result = RevDiffStr(mySTRvar1, mySTRvar2, False)
MsgBox result
End Sub
Display More
Cheers,
Peixe