Skip to main content
1 of 3

After reading a related post in the retailcoder blog - Enhancing VBA String Handling - and making some tests, I created this personal version of the first function. In many of my situations is important to know if a text is contained within another from specific positions:

'@Description "Returns True if found an ocurrence of one string within another from a specific position. False otherwise."
Public Function Contains(ByVal TextToLookIn As String, _
                         ByVal TextToLookFor As String, _
                         Optional ByVal FromPosition As Long = 1, _
                         Optional ByVal CaseSensitive As Boolean = False) _
As Boolean
  If TextToLookFor <> vbNullString Then
    Dim ComparisonMethod As VbCompareMethod
    If CaseSensitive Then
      ComparisonMethod = vbBinaryCompare
    Else
      ComparisonMethod = vbTextCompare
    End If
    Contains = CBool(InStr(FromPosition, TextToLookIn, TextToLookFor, ComparisonMethod))
  End If
End Function

In the InStr function if String2 (TextToLookFor in the function) is an empty string then the returned value is the start position (FromPosition in the function) so the function may erroneously return True in that cases.