Using a variable wildcard

Smurphster16

New Member
Joined
Feb 28, 2019
Messages
25
Hi guys I have the following code which allows me to open the latest file in my specified folder which contains the wildcard i specify - however the code only works when i hardcode the wildcard entry. But i want the wildcard to be a variable so that I can use a loop to open several most recent files in the folder - each containing a different wildcard.
In the code below I wanted to set c as the variable in the excel sheet and use this as the wildcard, bu instead of using the value i set for C it uses C itself

Any help on this would be much appreciated,

Thanks

VBA Code:
Sub NewestFile()

    Dim MyPath As String
    Dim MyFile As String
    Dim LatestFile As String
    Dim LatestDate As Date
    Dim LMD As Date
    
    C = Sheets("Sheet1").Range("OBR")
    MyPath = Sheets("Sheet1").Range("Desired_Path")
    If Right(MyPath, 1) <> "\" Then MyPath = MyPath & "\"
    
    MyFile = Dir(MyPath & "*C *.csv", vbNormal)
    If Len(MyFile) = 0 Then
        MsgBox "No files were found...", vbExclamation
        Exit Sub
    End If
    Do While Len(MyFile) > 0
        LMD = FileDateTime(MyPath & MyFile)
        If LMD > LatestDate Then
            LatestFile = MyFile
            LatestDate = LMD
        End If
        MyFile = Dir
    Loop
    Workbooks.Open MyPath & LatestFile

End Sub
 

Excel Facts

How can you turn a range sideways?
Copy the range. Select a blank cell. Right-click, Paste Special, then choose Transpose.
You need to concatenate the variable value into the folder path like this:

Code:
MyFile = Dir(MyPath & "*" & C & " *.csv", vbNormal)
 
Upvote 0
Try
VBA Code:
MyFile = Dir(MyPath & "*" & C & "*.csv", vbNormal)
 
Upvote 0

Forum statistics

Threads
1,215,009
Messages
6,122,674
Members
449,091
Latest member
peppernaut

We've detected that you are using an adblocker.

We have a great community of people providing Excel help here, but the hosting costs are enormous. You can help keep this site running by allowing ads on MrExcel.com.
Allow Ads at MrExcel

Which adblocker are you using?

Disable AdBlock

Follow these easy steps to disable AdBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the icon in the browser’s toolbar.
2)Click on the "Pause on this site" option.
Go back

Disable AdBlock Plus

Follow these easy steps to disable AdBlock Plus

1)Click on the icon in the browser’s toolbar.
2)Click on the toggle to disable it for "mrexcel.com".
Go back

Disable uBlock Origin

Follow these easy steps to disable uBlock Origin

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back

Disable uBlock

Follow these easy steps to disable uBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back
Back
Top