Pages

Sunday, April 20, 2014

Search a text in word documents and if found return the full path of document

Macro to search a text in the word documents saved in a folder and return the full document path of all documents which contains the text -

Sub search_text_in_word_docs()
    'search a text in the word documents saved in a folder and return the full document path of all documents which contains the text
    Dim filenm As String, folderpath As String
    Dim wordtocheck As String
    folderpath = "C:\Users\ADMIN\Desktop\sample files\" ' change folder here
    wordtocheck = "abc" ' change text to search here
    filenm = Dir(folderpath)
        While (filenm <> "")
            If InStr(filenm, ".doc") > 0 Then ' check word document
            If check_in_file(folderpath & filenm, wordtocheck) = True Then MsgBox folderpath & filenm
            End If
            filenm = Dir
        Wend
End Sub

Function check_in_file(filname As String, word_to_check As String) As Boolean
    Dim objWord As Object
    Dim objdoc As Object
    Dim content1 As String
    
    Set objWord = CreateObject("Word.Application")
    Set objdoc = objWord.Documents.Open(filname)
    
    content1 = " " & objdoc.Content.Text
    
    If InStr(UCase(content1), UCase(word_to_check)) <> 0 Then
        check_in_file = True
    Else
        check_in_file = False
    End If
    objdoc.Close
    Set objdoc = Nothing
    Set objWord = Nothing

End Function


No comments:

Post a Comment