tags:

views:

366

answers:

2

Thanks for the help on my previous question. With the suggestion I was able to read in the line of text from the Word document. I was then able to proceed to parse the line to pull out the file name.

I am now trying to initiate a file search using that file name. Does anyone have any suggestions on how to use MS Word Macro to initiate a text file search? I will need to find the file, open it, and then search within the text file.

Any help will be appreciated. Thank you!

+1  A: 

If you are doing it from Word, the easiest way would be to open the text file in Word and use Word's search functionality. That way you don't need to implement your own search functionality.

Just record a macro of this action: Open a text file in Word and search for a specific string (Ctrl-F). The result looks something like this:

Sub Macro1()

    Documents.Open FileName:="YourFile.txt", ConfirmConversions:=False, _
        ReadOnly:=False, AddToRecentFiles:=False, PasswordDocument:="", _
        PasswordTemplate:="", Revert:=False, WritePasswordDocument:="", _
        WritePasswordTemplate:="", Format:=wdOpenFormatAuto, XMLTransform:="", _
        Encoding:=1252

    Selection.Find.ClearFormatting

    With Selection.Find
        .Text = "YourSearchText"
        .Replacement.Text = ""
        .Forward = True
        .Wrap = wdFindContinue
        .Format = False
        .MatchCase = False
        .MatchWholeWord = False
        .MatchWildcards = False
        .MatchSoundsLike = False
        .MatchAllWordForms = False
    End With

    Selection.Find.Execute

    If Not Find Is Nothing Then
        ' your action here '
    End If
End Sub

You can then edit the recorded macro to suit your needs.

Edit: I see that I partly misunderstood your question. My answer only covers how to search a text file for a specific string, not how to search the file system for a list of files.

Treb
+2  A: 

To search, use Application.FileSearch:

(Note you'll have to manually copy & paste the URL since the automatic highlighter doesn't like parentheses)

http://msdn.microsoft.com/en-us/library/aa190819(office.10).aspx

Reading, use FileSystemObject:

http://www.webpagedeveloper.ws/FSRC/vba_code/File%20System%20Object%20code.html

Searching should be a simple matter of InStr from there.

Stu