excelvbaoffice365

If cell contains specific multiple words then


I need a line of code that looks at the cell and if it contains a set of words then it does something else:

If Range("A1").Value = "*Tree*" or "*Plant*" or "*Grass*" Then
'does something
else
'does something else
End If

I know this isn't the right code to achieve what I want but I cannot find the correct way to do this anywhere.


Solution

  • You can use Like

    Dim v, ws As Worksheet
    
    Set ws = ActiveSheet 'try to always use a specific sheet
    v = LCase(ws.Range("A1").Value) 'lower-case for comparisons, unless case is important
    
    If v Like "*tree*" or v Like "*plant*" or v Like "*grass*" Then
    'does something
    else
    'does something else
    End If
    

    Note this would not distinguish between (eg) "tree" and "treehouse", but it's not clear if you need to check for whole words only.

    A more re-useable version using a function and Instr:

    Sub tester()
        Dim txt As String
        txt = "this sentence contains some words"
        Debug.Print ContainsAny(txt, "dog", "horse", "some") '>> True
        Debug.Print ContainsAny(txt, "dog", "horse")         '>> False
    End Sub
    
    'Returns True if `txt` contains any of the words passed to `words`
    Function ContainsAny(txt As String, ParamArray words()) As Boolean
        Dim i As Long
        For i = LBound(words) To UBound(words)
            If InStr(1, txt, words(i), vbTextCompare) > 0 Then
                ContainsAny = True
                Exit Function
            End If
        Next i
    End Function