Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations John Tel on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Multiple String Search using InStr() 1

Status
Not open for further replies.

mytaurus2000

Technical User
Oct 4, 2006
138
US
I have code that finds the correct string in my find button, but how do i code to search for the next occurance.

For e.g. I can not believe that you can

If I hit the find button it will highlight the first occurence of can, but if I hit the find next it will hightlight the next occurence.

Code for the Find button

Private Sub btnFind_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnFind.Click
Target = txtTarget.Text
FoundPos = InStr(txtMemo.Text, Target)
txtMemo.SelectionStart = IIf(FoundPos > 0, FoundPos - 1, 0)
txtMemo.SelectionLength = IIf(FoundPos > 0, Len(Target), 0)
txtMemo.Focus()
btnFindNext.Enabled = IIf(FoundPos > 0, True, False)


End Sub

 
You need just need to keep track of the last position of the string in something like a global variable or get the current position you have highlighted the string at and start from there. InStr will allow you set the position in the string it starts from.

-I hate Microsoft!
-Forever and always forward.
 
I'm trying to avoid coding like

FirstPos = InStr(1, "Eventful adventure", "vent")
SecondPos = InStr(FirstPos + 1, "Eventful adventure", "vent")
ThirdPos = InStr(SecondPos +1, "Eventful adventure", "vent")

Is there a way to keep searching without continually getting the current position?
 
I would use regular expressions to do this.

[red]"... isn't sanity really just a one trick pony anyway?! I mean, all you get is one trick, rational thinking, but when you are good and crazy, oooh, oooh, oooh, the sky is the limit!" - The Tick[/red]
 
Don't use FirstPos, SecondPos, ThirdPos, etc. Use something more dynamic like an array. You can build your array by recursively calling a method, for example:

Code:
    Sub StringPosition(ByVal startplace As Integer, ByVal value As String, ByVal searchstring As String, ByRef indexarray As Integer())
        Dim index As Integer = -1
        index = value.IndexOf(searchstring, startplace)
        If index >= 0 Then 'An occurence was found, so add to the array and call this method again
            ReDim Preserve indexarray(indexarray.Length)
            indexarray(indexarray.Length - 1) = index
            [b]StringPosition(index + searchstring.Length, value, searchstring, indexarray)[/b]
        End If
    End Sub
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top