Multiple string search with InStr in VBA

前端 未结 3 1643
耶瑟儿~
耶瑟儿~ 2021-01-18 18:11

I am checking whether a Name textbox starts with Mr. Mrs. Ms. etc.

I created a function but I am not able to compare more than one string.

Here is my code.

3条回答
  •  陌清茗
    陌清茗 (楼主)
    2021-01-18 18:42

    Pass a list of tokens to search for using a ParamArray and loop each looking for a match.

    You can use vbTextCompare to enforce case sensitivity.

    Remember that starts with is different 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
    

    Or better with a RegEx to allow optional . and not match 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
    

提交回复
热议问题