Option Explicit
Private j As Long
Private i As Long
Private string1 As String
Private string2 As String
Private z As Long
Private blIsAMatchFoundBetweenStrings As Boolean
Private Sub Command1_Click()
string1 = "123456790123450"
string2 = "123456789012345"
blIsAMatchFoundBetweenStrings = False
IterateString
End Sub
'***
Public Sub CompareLongestMatch(ByVal string1 As String, _
ByVal string2 As String)
Dim strTmpString As String
' when a match is found this sub starts, the value of i is carried on
' from the previous IterateString sub
' string1 = "123456790123450"
' string2 = "123456789012345"
' so if i = 1 run through this till i <> j
' first run up till 8, finds, 1234567
Do Until Mid$(string1, i, 1) <> Mid$(string2, j, 1)
strTmpString = strTmpString & Mid$(string1, i, 1)
j = j + 1
i = i + 1
DoEvents
Loop
' the length of all Consecutive letters found
If Len(strTmpString) > 1 Then
z = z + Len(strTmpString)
End If
strTmpString = vbNullString
End Sub
Private Sub IterateString()
i = 1
j = 1
' when the length of string2 = 0, end, will always reach 0
If Len(string2) = 0 Then
MsgBox z
z = 0
Exit Sub
End If
'string1 = "123456790123450"
'string2 = "123456789012345"
For i = 1 To Len(string1)
' run through string1 1 char at a time and compare each to first char in string2
' j stays at 1 for first loop
If Mid$(string1, i, 1) = Mid$(string2, j, 1) Then
'if a match is found then find out how long it goes on for ***
CompareLongestMatch string1, string2
' redim string2 so its string2 -
' so for the above strings 1234567 are found so string2 becomes
' 89012345, string1 doesn't change
' 8 isnt found so string2 =9012345 then
' 9012345 so strin2 = 0
string2 = Mid$(string2, j, Len(string2))
DoEvents
blIsAMatchFoundBetweenStrings = False
Exit For
End If
Next i
'if no match is found then that character must be a single char then remove it
' so this next condition only gets entered if no match was found
If blIsAMatchFoundBetweenStrings Then
' so redim string , string2 - 1
string2 = Right$(string2, Len(string2) - 1)
End If
' set the flag back to true
' when a match is found flag sets to false
blIsAMatchFoundBetweenStrings = True
' recursive
IterateString
End Sub