I am using Excel VBA to validate the accuracy of a string. I need to make sure a variable substring is not duplicated. I have used a bulky ElseIf method, but it is missing instances where more than one substring was used. The first substring passed, but it does not loop back to check on the next substring.
Dim chkstring As String, phrase As String
If InStr(chkstring, "BAG") > 0 Then
phrase = "BAG"
ElseIf InStr(chkstring, "NOTE") > 0 Then
phrase = "NOTE"
ElseIf InStr(chkstring, "MEMO") > 0 Then
phrase = "MEMO"
Else
phrase = ""
End If
If phrase <> "" Then
OccurCount = findOccurancesCount(chkstring, phrase)
If OccurCount > 1 Then
'highlight cell
End If
End If
Then I use
Function findOccurancesCount(chkstring, phrase)
OccurCount = 0
y = 1
Do
foundPosition = InStr(y, chkstring, phrase) 'searching from i position
If foundPosition > 0 Then 'substring is found at foundPosition index
OccurCount = OccurCount + 1 'count this occurance
y = foundPosition + 1 'searching from x+1 on the next cycle
End If
Loop While foundPosition <> 0
findOccurancesCount = OccurCount
End Function
This is fine if the chkstring = "BAG BAG" But if there is more than one phrase it will not go back to look for others. For example: "BAG NOTE NOTE"
"BAG" passes the check, but it does not go back to look for "NOTE".
I am wondering if there is a more effective way to combine all of the possible phrases then check to see if any of them are in the chkstring more than one? Thanks!