How to Make Excel VBA Find a CSV File When Its Name Changes
Question details
Find or reference a CSV file in an Excel VBA macro without hard-coding a filename that changes with the date and time.

- Product
- Microsoft Excel VBA
- Device & OS
- not provided
- Scenario
- A macro needs to work with a CSV file whose name includes a changing timestamp.
- Observed behavior
- The macro should identify the intended CSV file through a stable filename pattern, user selection, or an already-open workbook.
Identify the CSV folder and the part of the filename that stays the same. If several files may match, decide whether the user should select the intended file rather than relying on the first match.
Find a Matching CSV File with the VBA Dir Function
Use a wildcard when the file is in a known folder and its name has a consistent suffix.
In Excel, press Alt+F11, then choose Insert > Module.
Paste this example into the module: Sub OpenMatchingCSV() Dim fileName As String Dim folderPath As String folderPath = "C:\Data\" fileName = Dir(folderPath & "*_detail_inbound.csv") If fileName = "" Then MsgBox "No matching CSV file was found.", vbExclamation Exit Sub End If Workbooks.Open folderPath & fileName End Sub
Replace C:\Data\ with your CSV folder path, including the trailing separator, and change the wildcard pattern to match your filename. Run OpenMatchingCSV from the VBA editor or Excel's macro list.

Select the CSV File with a File Picker
Use this approach when multiple files may match or the CSV folder changes.
Reference the CSV as the Active Workbook
Use this option when the CSV is already open and selected before the macro runs.
Open and Review CSV Files in WPS Office
WPS Office is a free, lightweight alternative with a familiar spreadsheet interface. Open CSV and Excel files in WPS Spreadsheets to make migration easier; Excel VBA macro compatibility depends on your WPS edition and configuration.

Frequently Asked Questions
How do I match a changing date in a CSV filename?
Use an asterisk in a Dir pattern, such as Dir(folderPath & "*_detail_inbound.csv"), to match any prefix before the fixed suffix.
Does Dir automatically find the newest CSV file?
No. Dir returns the first matching filename, not necessarily the newest. Use a file picker or add logic to compare file timestamps if the newest file is required.
What happens if the user cancels the file picker?
Application.GetOpenFilename returns False when canceled. Check for False and exit the macro before calling Workbooks.Open.
Can I use a CSV that is already open?
Yes. Activate the CSV workbook in Excel, then use ActiveWorkbook or store ActiveSheet in a Worksheet variable before switching to another workbook.




