Multiple string search with InStr in VBA

前端 未结 3 1644
耶瑟儿~
耶瑟儿~ 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:52

    This is my version of @AlexK great answer. While it solved the OP's original problem I wanted to share a more generalized answer for others to benefit from.

    Here is how I used the Function:

    Public Sub InString_Test()
    
    Dim WS As Worksheet
    Set WS = ThisWorkbook.Sheets("Sheet1")
    
    Dim rcell As Range, rng As Range
    Set rng = WS.Range("A1:A" & WS.UsedRange.Rows.Count)
    For Each rcell In rng.Cells
    
    If InStrFunc(Range(rcell.Address), "TEST", "CAT") Then
       MsgBox "String Found in " & rcell.Address
    End If
    
    Next rcell
    
    End Sub
    
    Function InStrFunc(strCheck As String, ParamArray anyOf()) As Boolean
        Dim item As Long
        For item = 0 To UBound(anyOf)
            If InStr(1, strCheck, anyOf(item), vbTextCompare) <> 0 Then
                InStrFunc = True
                Exit Function
            End If
        Next
    End Function
    

提交回复
热议问题