Multiple Search Strings Using InStr Function in VBA

I check if the Name text box starts with Mr Mrs.Ms, etc. or not, I created a function, but I was stuck in an instant, I can not compare more than from a string. Here is my sample plz code guide me ...

    'Checking whether name is starts with Mr./Mrs./Ms./Dr. or not
         If Not FindString(LCase(Me.gname.Value), LCase("Mr")) Then
             MsgBox "Consumer Name Starts with Mr./Mrs./Ms./Dr. Check Consumer Name"
             Cancel = True
             Exit Sub
         End If

    'Here is the Find String function i created
         Function FindString(strCheck As String, strFind As String) As Boolean
             Dim intPos As Integer

             intPos = 0
             intPos = InStr(strCheck, strFind)
             FindString = intPos > 0
         End Function
+4
source share
2 answers

Pass strFind as a group of strings separated by an ex delimiter: -

FindString(LCase(Me.gname.Value), LCase("Mr;Mrs;Ms;Dr"))

Now separate them and compare using a loop.

Arr = Split(strFind,";")
Flag = 0

For Each str in Arr    
  If InStr(strCheck, str) > 0 Then
  Flag = 1    
  End If
Next
If Flag = 1 Then
  FindString = True
Else
  FindString = False
End If
+2
source

Pass a list of tokens to search with ParamArrayand loops, each of which looks for a match.

You can use vbTextCompareto provide case sensitivity.

Remember that starting with differs from contains.

'// you can pass as many prefixes as you like
If StringStarts(Me.gname.Value, "Mr", "Mrs", "Dr", "Supreme Commander", "Capt.") Then
    MsgBox "Consumer Name Starts with Mr./Mrs./Ms./Dr. Check Consumer Name"

... 

Function StringStarts(strCheck As String, ParamArray anyOf()) As Boolean
    Dim item As Long
    For item = 0 To UBound(anyOf)
        If InStr(1, strCheck, anyOf(item), vbTextCompare) = 1 Then
            StringStarts = True
            Exit Function
        End If
    Next
End Function

RegEx . Mruku

StringStarts(Me.gname.Value, "Mr|Mrs|Ms|Dr")

...

Function StringStarts(strCheck As String, options As String) As Boolean
    With CreateObject("VBScript.RegExp")
        .IgnoreCase = True
        .Pattern = "^(" & options & ")\.*\b"

        StringStarts = .Test(strCheck)
    End With
End Function
+2

All Articles