Results 1 to 4 of 4

Thread: [RESOLVED] Searching in a text file with array of words

  1. #1

    Thread Starter
    Frenzied Member
    Join Date
    Nov 2005
    Posts
    1,834

    Resolved [RESOLVED] Searching in a text file with array of words

    Hi, normally I'm using the code below to search for words in a text file and display the entire line when a match has been found.

    VB Code:
    1. Private Sub Command1_Click()
    2. Dim sLines As String
    3.  
    4. Open "C:\textfile.txt" For Input As #1
    5.   Do While Not EOF(1)
    6.    Line Input #1, sLines
    7.     If InStr(1, sLines, "horse") And InStr(1, sLines, "fish") Then
    8.      Text1.Text = Text1.Text & sLines & vbCrLf
    9.     End If
    10.   DoEvents
    11.   Loop
    12. Close #1
    13.  
    14. End Sub
    How can I do the same thing when I have the words (horse and fish) stored in an array? Normally I can replace "Horse" with strArray(0) and "Fish" with strArray(1), but the number of words in the array is always different.

    In other words, how do I use an array with "If InStr(1, sLines, ????????) Then" when the amount of search words is always different?

    (btw, the text file can be 50MB big)

  2. #2
    Super Moderator si_the_geek's Avatar
    Join Date
    Jul 2002
    Location
    Bristol, UK
    Posts
    41,974

    Re: Searching in a text file with array of words

    You need to use a loop to go thru all of the items, and store the result of the checks - if any fail then it isn't a match, so don't add the text.
    VB Code:
    1. Dim booIsFound as Boolean
    2. Dim lngCounter as Long
    3.     For lngCounter = 0 To UBound(strArray)
    4.       booIsFound = (InStr(1, sLines, strArray(lngCounter)) > 0)
    5. 'the line above is the same as:
    6.       'If InStr(1, sLines, strArray(lngCounter)) Then
    7.       '  booIsFound = True
    8.       'Else
    9.       '  booIsFound = False
    10.       'End If
    11.       If Not booIsFound Then Exit For  'no point checking the others!
    12.     Next lngCounter
    13.     If booIsFound Then
    14.      Text1.Text = Text1.Text & sLines & vbCrLf
    15.     End If

  3. #3

    Thread Starter
    Frenzied Member
    Join Date
    Nov 2005
    Posts
    1,834

    Re: Searching in a text file with array of words

    Thank you

  4. #4
    Junior Member
    Join Date
    Nov 2006
    Posts
    22

    Re: [RESOLVED] Searching in a text file with array of words

    Too Thanks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width