Link to home
Start Free TrialLog in
Avatar of LizzJ
LizzJ

asked on

Find text in word document using VBA

Hi Experts,

I have hundred plus word documents. What i want is to write a simple VBA program to list out distinct text with "[]" in each document. E.g.

I was not born in [New York], instead I was born in [LA], but I'm moving from [LA] to [New York]. But I love [San Francisco] the most.

The result should be:
New York
LA
San Francisco

Please help. This is very urgent! If not, I will have to go through the hundred documents...

Many Thanks.
Avatar of werafa
werafa

Try using the maxcro recorder, and record a macro to perform a search for the words you are looking for.

then edit the macro to pass a true/false value, and read the file name property if true.

I am not very familiar with vba in word, but I also believe that vba can read the file names in a directory, and could therefore open them one by one, test for the presence of the search words, record the file name of test = true files in an array, and print the array to a spreadsheet, doc file or paper.

can anyone else add details?
Avatar of LizzJ

ASKER

werafa,

You've got the idea half correct. I only want those text enclosed with square brackets, but i don't know exactly what those text are, so don't think macro can achieve this.

I found the following solution from a similar question just now. And now i'm able to search for the first content i want. But exactly, like what you mentioned, to loop through the whole document and also all these 100 documents one by one and print the text in a spreadsheet?


Selection.Find.ClearFormatting
            With Selection.Find
                 .Text = "["
                 .Replacement.Text = ""
                 .Forward = True
                 .Wrap = wdFindContinue
             End With
            Selection.Find.Execute
            
            With Selection
                .StartIsActive = False
                .Extend Character:="]"
            End With
            Set rngHereIAm = Selection.Range
            'Ref = rngHereIAm.Text ' This would get the contents with the brackets
            Ref = Mid(rngHereIAm.Text, InStr(rngHereIAm.Text, "[") + 1, _
            (InStr(rngHereIAm.Text, "]") - (InStr(rngHereIAm.Text, "[") + 1)))
            Debug.Print Ref
          
            Ref = ""
            Set rngHereIAm = Nothing

Open in new window

ASKER CERTIFIED SOLUTION
Avatar of GrahamSkan
GrahamSkan
Flag of United Kingdom of Great Britain and Northern Ireland image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of LizzJ

ASKER

GrahamSkan,

This works perfect. Thanks a lot!