String Functions

Finding text

To find if a string contains another string, you can use InStr and InStrRev (InStrRev is only in VB6). These return the first and last positions of a string contained in another string, respectively. They both use the following syntax:

InStr$(Start,StringToSearch,StringToFind, SearchMode)

Start is an optional figure representing the position to start searching the string. StringToSearch contains the string that you want to search. StringToFind contains the string that you want to find. The following code gets the text from txtFindString and highlights the first occurrence of that string in txtSearchString. vbTextCompare tells the InStr function to find matching strings, regardless of case. Use vbBinaryCompare for the search to be case sensitive.

Sub Command1_Click()
    ' Get the first occurrence of the string
    StringPos = InStr(1, txtSearchString, txtFindString, vbTextCompare)
    If StringPos = 0 Then
        ' If StringPos returns 0, then the string is not found
        Msgbox "String not found"
    Else
        ' Get the length of the string to find
        StringLen = Len(txtFindString)
        ' Set the starting position of the selection
        txtSearchString.SelStart = StringPos
        ' Set the selection length
        txtSearchString.SelLength = StringLength
    End If
End Sub

You could change InStr to InStrRev to find the last occurrence of the Find String. 

You might also like...

Comments

About the author

James Crowley

James Crowley United Kingdom

James first started this website when learning Visual Basic back in 1999 whilst studying his GCSEs. The site grew steadily over the years while being run as a hobby - to a regular monthly audien...

Interested in writing for us? Find out more.

Contribute

Why not write for us? Or you could submit an event or a user group in your area. Alternatively just tell us what you think!

Our tools

We've got automatic conversion tools to convert C# to VB.NET, VB.NET to C#. Also you can compress javascript and compress css and generate sql connection strings.

“In order to understand recursion, one must first understand recursion.”