Wednesday, November 11, 2009

How to search a string in a word document

Below function searches for a string in specified document and returns true if it finds the string else returns false.

function findTextInWord(doc_file,looking_for)
Set objWord = CreateObject("Word.Application")
Set objDoc = objWord.Documents.Open(doc_file)

'Create a Range object of the file's contents
Set objRange = objDoc.Content 'Is equivalent to: Set objRange = Range()

'Grab the text within that range
strContents = objRange.Text

'Remove any non-printing characters such as bullets
strContents = objWord.CleanString(strContents)


objDoc.close
set objDoc=Nothing

if instr(strContents,looking_for)> 0 then
findTextInWord=true
else
findTextInWord=false
end if
end Function

if findTextInWord("path of the word document","search string") then
msgbox "Found"
else
msgbox "Not found"
end if

No comments: