ana bel
ana bel

Reputation: 187

Open a workbook without knowing the exact name

so i searched but didnt find something good for my use , i have a folder where i will import an excel file , this excel file will have a different name everytime how i can open it with vba , thank you

Upvotes: 1

Views: 1992

Answers (1)

Kostas K.
Kostas K.

Reputation: 8518

You can get the file name using the Dir function and multiple character (*) wildcard.

Const Path As String = "C:\Test"

Dim filename As String
    filename = Dir(Path & "\*.xlsx")

If Len(filename) > 0 Then
    ' Do your work 
    ' Remember 'filename' only holds the file name
    ' you will need to attach the rest of the path to get the full directory.
End If 

Note: If there's only one file in the folder you will not have any issues, however if the folder contains multiple files (matching the above pattern), you will need to either loop or provide additional file name characters to the function.

An example:

File name: daily_report_20190404.xlsx

filename = Dir(Path & "\daily_report_*.xlsx")

Hope this helps.

Upvotes: 1

Related Questions