We help IT Professionals succeed at work.

How can I open a file then search its contents for a string

brianshoenhair
on
417 Views
Last Modified: 2008-01-16
Please give an example

Must be able to use wildcards

How can I open a file then search its contents for a string.
If the string is found it will immediately stop the search, close the file, then return a True value.
If the string is not found it will close the file then return a False value.
Comment
Watch Question

Top Expert 2004

Commented:
Private Sub Command1_Click()
MsgBox FindInFile("mypath & filename", "string to search")
End Sub

Private Function FindInFile(ByVal fnFileName As String, fnSearch As String) As Boolean
Dim myLine As String
FindInFile = False
Open fnFileName For Input As #1
    Do Until EOF(1)
        Line Input #1, myLine
            If InStr(1, myLine, fnSearch) > 0 Then
                FindInFile = True
                Exit Do
            End If
    Loop
Close #1
End Function

S

Author

Commented:
Wildcards are a must

Shauli, your example does not work with wildcards
Top Expert 2004

Commented:
Using InStr you don't really need a wildcard, as it looks for any part of a string. However, if your user is using a wildcard, then:

Private Sub Command1_Click()
MsgBox FindInFile("C:\My Documents\products.txt", "sha*")
End Sub

Private Function FindInFile(ByVal fnFileName As String, fnSearch As String) As Boolean
Dim myLine As String
FindInFile = False
Open fnFileName For Input As #1
    Do Until EOF(1)
        Line Input #1, myLine
            If InStr(1, myLine, Replace(fnSearch, "*", "")) > 0 Then
                FindInFile = True
                Exit Do
            End If
    Loop
Close #1
End Function

S
Top Expert 2004

Commented:
Of course:

Private Sub Command1_Click()
MsgBox FindInFile("your path & file", "*your string*")
End Sub

:)

S

Commented:
C if this is of any help to you

http://www.aivosto.com/regexpr.html
Unlock this solution and get a sample of our free trial.
(No credit card required)
UNLOCK SOLUTION

Author

Commented:
Thank You everyone for your response.

The Like Operator is the best for what I am trying to do.

Points will go to sokolovsky.
Unlock the solution to this question.
Thanks for using Experts Exchange.

Please provide your email to receive a sample view!

*This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.

OR

Please enter a first name

Please enter a last name

8+ characters (letters, numbers, and a symbol)

By clicking, you agree to the Terms of Use and Privacy Policy.