Home » excel » excel – VBA wildcard statement

excel – VBA wildcard statement

Posted by: admin April 23, 2020 Leave a comment


VBA is having difficulty finding my files using the wildcard *. Is there an issue with the syntax in this statement?

Workbooks.Open Filename:="C:\Users\xxxx\Desktop\xxxx Charts\xxxx Source Files\*_history_" & myYear & "-" & myMonth & "-" & mydate & "_" & myHour & "h" & myminute & "m" & "00s_xxx_all_xxx.csv"

where the wildcard I’m trying to match is Capital Letter, number,number,number, hyphen, number, number, number, number like this: A999-9999

Note: if I type out the A999-9999 (for example) it runs, so there does not appear to be an issue with the variables or the rest of the statement.

Thank you for any assistance.

How to&Answers:

Something like this pointed at your directory to find all csv files matching “.csv” with a second stage check to open the first file matching your desired file pattern

Sub LoopThroughFiles()
    Dim StrFile As String
    Dim bFound As Boolean
    Dim WB As Workbook
    StrFile = Dir("c:\temp\*-*.csv")
    Do While Len(StrFile) > 0
    If StrFile Like "[A-Z]




#.csv" Then Set WB = Workbooks.Open("c:\temp\" & StrFile) bFound = True Exit Do Else StrFile = Dir End If Loop If Not bFound Then MsgBox "File not found", vbCritical End Sub