Home » excel » excel vba – Search Multiple file extension

excel vba – Search Multiple file extension

Posted by: admin April 23, 2020 Leave a comment

Questions:

I have a vba syntax which search for only pdf files.I wanted to know what changes do I need to make in the below code so that it can search docx and similar ext files as well.

If pfile <> "" And Right(pfile, 3) = "pdf" Then
Set obMail = Outlook.CreateItem(olMailItem)
How to&Answers:

First change your Dir command to look for folder & "\*.*. While you’ve neglected to incude that important postion of your code, a Dir list isn’t going to return anything that is outside of its file mask. Next, pull the file extension off the right hand end and compare it to a list of desired file extensions.

dim folder as string, pfile as string, ext as string
folder = "c:\temp"
pfile = Dir(folder & "\*.*")
do while cbool(len(pfile))
    ext = chr(32) & lcase(trim(right(replace(pfile, chr(46), space(99)), 99))) & chr(32)
    if cbool(instr(1, " pdf docx doc xls xlsx ", ext, vbTextCompare)) then
        'do something with the matching file
    end if
    pfile = Dir
loop