Link to home
Start Free TrialLog in
Avatar of terpsichore
terpsichore

asked on

Find filename in directory to match components

Dear experts -
I am trying to: a) determine if a file exists in a given directory; and b) store the full name of that file (with path) to a variable.

Specifically, I want to see if there is a file in a given directory where: a) the first part of the filename; and b) end part of the filename match a given pattern (for example, in the directory: "J:\purchase orders\" is there a file that begins with the string "2001_ABC1" and ends with the string "_07.pdf".

Any thoughts are greatly appreciated!
Avatar of danishani
danishani
Flag of United States of America image

Try this, late binding version of using the FileSystemObject:

Private Sub Command13_Click()

Dim SourceFolderName As String

Dim fso As Object
Dim SourceFolder As Object
Dim Subfolder As Object
Dim FileItem As Object

Dim myVar As String


SourceFolderName = "C:\YourPathNameHere\"

Set fso = CreateObject("Scripting.filesystemobject")


On Error GoTo Err_Handler
   
    Set SourceFolder = fso.GetFolder(SourceFolderName)
   
    For Each FileItem In SourceFolder.Files
       If Right(FileItem.Name, 7) = "_07.pdf" And Left(FileItem.Name, 9) = "2001_ABC1" Then
       
       myVar = FileItem.Path
       Debug.Print myVar
                   
       End If
   
    Next
   
Exit_Handler:
    Set FileItem = Nothing
    Set SourceFolder = Nothing
    Set fso = Nothing
   
    Exit Sub
   

Err_Handler:
    MsgBox "Error " & Err.Number & ": " & Err.Description
    Resume Exit_Handler


End Sub
ASKER CERTIFIED SOLUTION
Avatar of Boyd (HiTechCoach) Trimmell, Microsoft Access MVP 2010-2015
Boyd (HiTechCoach) Trimmell, Microsoft Access MVP 2010-2015
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of terpsichore
terpsichore

ASKER

simple, works great