Home » excel » excel vba – custom formula for Contains()

excel vba – custom formula for Contains()

Posted by: admin May 14, 2020 Leave a comment

Questions:

If i had a column like:

ColumnA
-------
NUMBER
VARCHAR(50 BYTE)
TIMESTAMP

I’m looking for a vba function that would work like so:

contains(“string to search for”, cell to search it in)
ie. =contains(“VARCHAR”,A2)
and if the cell does contain it (anywhere in the cell – doesn’t have to start or end the cell) then populate the cell (that uses the function) with “T” else “F”.

so in my example:

ColumnB
-------
F
T
F

Also could I then use this function inside other VBA code like so:

If Len(A2) > 10 and contains("CHAR",A2) Then
 //do stuff
End If

If they have to be separate functions (to use in cells returning “T”/”F” and to use in other VBA code), please provide both.

How to&Answers:

You want VBA’s InStr

For example in a module;

Public Function Contains(Text As String, Cell As Range) As String
   If InStr(1, Cell.Value, Text, vbTextCompare) Then '//case insensitive
       Contains = "T"
   Else
       Contains = "F"
   End If
End Function

Enables =Contains("blah", A1) in a worksheet