Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

VBA for returning the name of a file. 1

Status
Not open for further replies.

Hanss

Technical User
Feb 15, 2001
85
CH
Hi,

I have a form with a button and a field called "file"

When I push the button I would like the code to find the name of an unknown file in C:\test\ and then put it in the field "file"

What I have tried:

Dim fso As Object
Set fso = CreateObject("Scripting.FileSystemObject")
Me.Name = fso.GetFileName("c:\test\*.*")

Many thanks!
Hanss
Zurich

 
Do you want to display the names of all of the files found in C:\test\ and then select one manually?

or do you want to return the name of the only file found there?

or something else?

Greg
People demand freedom of speech as a compensation for the freedom of thought which they seldom use. Kierkegaard
 
Greg,

Thank you for your interest! I want to return the name of the only file found there

There is only one file in C:\test\ which was created by a scanner. For example:

081010200131.pdf

With kind regards,
Hanss

 
To get all of the names of files

Code:
    Dim fso As New FileSystemObject
    Dim fsoFold As scripting.Folder
    Dim FileNames As scripting.Files
    Dim FileID As scripting.File
    
   
   Set fsoFold = fso.GetFolder("c:\test")

    Set FileNames = fsoFold.Files
    For Each FileID In FileNames
 
   '         Debug.Print FileID.name
        Me.Name = FileID.Name
    Next

There's a direct method for getting the name of the first file without using a for - next loop, but I'll have to look it up tomorrow.

Greg
People demand freedom of speech as a compensation for the freedom of thought which they seldom use. Kierkegaard
 
Hi Greg,

Thank you VERY much for your help! Your code works fine. If you do find the direct method, that would be interesting, but I can live very well with what you have given me.

Kind regards,
Hanss
Zurich
 
I cannot seem to find a file system object direct read method. My memory must be failing me.

On the other hand you could simply use the DIR function:
Code:
' Returns filename with specified extension. If more than one *.pdf
' file exists, the first file found is returned.
Me.Name = Dir("C:\test\*.pdf")

Example taken (almost) directly from:

Greg
People demand freedom of speech as a compensation for the freedom of thought which they seldom use. Kierkegaard
 
Greg,

Thank you also for this really short version. It works great!

Hanss
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top