• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 149
  • Last Modified:

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?
0
Prioritypub
Asked:
Prioritypub
  • 2
1 Solution
 
mvidasCommented:
Prioritypub,

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")

Matt
0
 
mvidasCommented:
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

Matt
0

Featured Post

Concerto's Cloud Advisory Services

Want to avoid the missteps to gaining all the benefits of the cloud? Learn more about the different assessment options from our Cloud Advisory team.

  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now