Home » excel » vba – Excel Macro to search for files based on a keyword and return true if present

vba – Excel Macro to search for files based on a keyword and return true if present

Posted by: admin May 14, 2020 Leave a comment

Questions:

Can someone help me out with a excel VBA macro to search for files in various directories provide in column B, based on keywords given in column A and return “File Present”/”File Not Present” in column C.

Example

Keyword | FolderPath | Result

1234 | E:\Documents\ABC

Apple | F:\

File2 | E:\Documents\Test\

I’m new to excel Macros. Please help me out!

Thanks in advance!

How to&Answers:

Give this a try:

Sub IsItThere()
    Dim KeyWd As String
    Dim Pathh As String, fName As String
    Dim N As Long, J As Long
    N = Cells(Rows.Count, "A").End(xlUp).Row
    For J = 1 To N
        KeyWd = Cells(J, 1).Value
        Pathh = Cells(J, 2).Value
        If Right(Pathh, 1) = "\" Then
            Pathh = Mid(Pathh, 1, Len(Pathh) - 1)
        End If
        Set objShell = CreateObject("Shell.Application")
        Set objFolder = objShell.Namespace((Pathh))

        For Each strFileName In objFolder.Items
            fName = objFolder.GetDetailsOf(strFileName, 0)
            If InStr(1, fName, KeyWd) > 0 Then
                Cells(J, 3).Value = "File Present"
                GoTo NextRecord
            End If
        Next
        Cells(J, 3).Value = "File Not Present"
NextRecord:
        Set objFolder = Nothing
        Set objShell = Nothing
    Next J
End Sub