A macro command that will open an unknown file in a known folder?

I have an Excel file in a folder with a name that will often change. I need to open that file and copy contents from it to another Excel file. I have the macro written to perform all the tasks, except if I don't know what the name of the file will be when the macro is run, so how can I open it?  It will be the only file in this folder, and the folder name will never change.  Is there a command line that will rename the file (without knowing what that file name is) if I know the folder name?
Who is Participating?

The Dir() function returns filenames from a specified path.  You could use that to return the file name.  Since you said there will only be one file, I've written this to only return the first file found.  If no files are found, it will return a zero-length string:

Function FirstFileName(ByVal ThePath As String) As String
 If Right(ThePath, 1) <> "\" Then ThePath = ThePath & "\"
 FirstFileName = Dir(ThePath)
End Function

If there could be non-xls files there, you can narrow it down to only look for .xls files:

 FirstFileName = Dir(ThePath & "*.xls")

Sorry, I should have given you a sample usage of this:

 Dim vFile As String
 vFile = FirstFileName("C:\foldername")
 If Len(vFile) > 0 Then
  Workbooks.Open vFile
 End If

Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.