Wednesday, April 30, 2014

How to search for a specific string in a MS Word document

The following example uses Word object methods to open a Microsoft Word Document and retrieve paragraphs from it. Then the InStr VBScript method is used to check for the word “contract.”


Example:

Dim wrdApp
Dim wrdDoc
Dim tString, tRange
Dim p, startRange, endRange
Dim searchString

‘Create the Word Object
Set wrdApp = CreateObject(”Word.Application”)
Set wrdDoc = wrdApp.Documents.Open(”C:\Temp\Word_Doc.doc”)     ‘replace the file with your MSDoc
searchString = “contract”                                   ‘replace this with the text you’re searching for

With wrdDoc
     For p = 1 To .Paragraphs.Count
          startRange = .Paragraphs(p).Range.Start
          endRange = .Paragraphs(p).Range.End
          Set tRange = .Range(startRange, endRange)
          tString = tRange.Text
          tString = Left(tString, Len(tString) - 1)                           ‘exclude the paragraph-mark
          If InStr(1, tString, searchString) > 0 Then                     ‘check if the text has the content you want
               
               msgbox “Yes! ” & searchString & ” is present”
         Exit For
          End If
     Next
.Close                    ‘close the document
End With

wrdApp.Quit      ‘close the Word application

Set wrdDoc = Nothing

No comments: